Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AngularJS An Introduction to Two-Way Data Binding Two-Way Binding: watchers

Matthew Kosloski
Matthew Kosloski
8,932 Points

Cannot create $watch with Angular?

What's wrong with this code? It's the same as the code Alex used, but without the factory. Also, how does Angular know what the values are for newValue and oldValue? I didn't give them values, I just passed them in as parameters?

app.js
angular.module('myApp', [])
.controller('myController', function ($scope, $http) {
  $scope.user = {name: 'Alex', id: 123};

  getUserData = function (id) {
    console.log('Getting user with ID: ' + id);
  }

$scope.$watch('user.id', function(newValue, oldValue){
      if (newValue) {
        api.getUserData($scope.user.id);
      }
    })

});
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <title>Angular.js</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <script src="app.js"></script>
</head>
<body ng-controller="myController">

  <input type="text" ng-model="user.id" />

</body>
</html>

1 Answer

I think the problem is that you want to observe ($watch) the id in the user object. As per the documentation writes, if you want to do a "deep" $watch, so you want to use the callback if any key has changed on the object, you have to use the $wath as per below:

$scope.$watch('user.id', function (newVal, oldVal) { /* Some code here */ }, true);

Please note the third argument!