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

Watcher Challenge

Hi guys,

During Angular's Challenge, what's missing in my code?

Question:Create a watcher that binds to the property user.id and, if it's set, calls the function getUserData with the new ID.

Error - Bummer! You need to create a watcher for the user.id property, and call getUserData within it.

See code below for your feedbacks please.

UPDATE:

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);
  }

  // YOUR CODE HERE
  $scope.$watch('user.id', function (getUserData) {
    if (getUserData) {
      $scope.saveUser($scope.user);
    }
  })
});
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>

Hugo Paz

4 Answers

I was having the same problem and the below answer was the passing solution I came up with. I hope this helps you.

$scope.$watch('user.id', function(id){  
    if(id){
        getUserData(id);
    }
})
Robert Ramirez
Robert Ramirez
3,644 Points

I used the template given in the video and instead of using the ID I used newValue which is the same as ID

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

Looks like you're missing a closing brace for the last $scope block.

Ah I see, thank you! curtis allen