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

Daniel Hildreth
Daniel Hildreth
16,170 Points

Two-Way Binding: Watchers AngularJS Challenge Help

So I am having trouble with the last challenge in this Two-Way Binding course in AngularJS. It asks me to "Create a watcher that binds to the property user.id and, if it's set, calls the function getUserData with the new ID." What is wrong with the ode I have?

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 (newId, oldId) {
    if (newId) {
      api.getUserData($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>

1 Answer

andi mitre
STAFF
andi mitre
Treehouse Guest Teacher

Hey Daniel, very close..you want to call the getUserData function with the newId and add a semicolon.

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 (newId, oldId) {
    if (newId) {
      getUserData(newId);
    };
  });
});

Cheers