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 trialIsrael Bautista
2,391 Pointsso this was my attempt to solve this but didn't worked, not sure why not, the lecture is not very helpful :(
$scope.$watch('user.id', function(newValue, oldValue){ if(newValue){ $scope.user = getUserData(id); } })
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){
$scope.user = getUserData(id);
}
})
});
<!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>
2 Answers
Salman Akram
Courses Plus Student 40,065 PointsI had similar issue with Two-Way Binding for Watcher, here's explain by Curtis in better example
Colin Bell
29,679 PointsThis question is asking you to watch value of the user.id. If it changes to a new value, take that same new value and run it through the getUserData() function.
In this case, it wants to the check if user.id changes. If it does change (i.e. if it gets a new Value), take that new value and log it to the console preceded by the string "Getting user with ID:"
You don't need to add $scope.user before getUserData. You've already set up your scope with the line
$scope.$watch('user.id',function(newValue, oldValue)
If you run:
$scope.$watch('user.id',function(newValue, oldValue) {
if(newValue) { // If this user.id receives a newValue is true, then
getUserData(newValue); // Take that same newValue and run it through getUserData
}
})
and click on the preview tab and open up the console on your browser, you should see something like this: