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

Why do we pass in the desired object property to watch as a string, instead of the literal notation?

I was just wondering why we do this in angular -- why pass it as a string, instead of explicitly passing the property?

i.e, we do this:

  $scope.$watch('user.id', function(newVal, oldVal){
    //...
  });

instead of:

  $scope.$watch(user.id, function(newVal, oldVal){
    //...
  });
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(newVal, oldVal){
    getUserData(newVal);
  });

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