I want to create a $watch in a directive to a specific part of a json object but it doesn't seem to accept the syntax (no errors appear, but it never goes inside the watch)
link: function (scope, element) {
scope.JsonObject={
profs:{
prof1:[{
name:example1a,
id:example1b
}],
prof2:[{
name:example2a,
id:example2b
}]
}
}
scope.teachers=scope.JsonObject['profs']
//until here all ok
for ( var teacher in scope.teachers){
//stuff to do
console.log("creating watch of " + teacher);
scope.$watch('teachers[teacher]', function() { //here seems to be the problem (it doesnt seem to accept JsonObject.teacher)
//stuff to do
}, true);
}
Previously, teachers[teacher] was undefined because there were no ' '(quotes)
around the teacher.
for (var teacher in $scope.teachers){
$scope.$watch("teachers['"+ teacher +"']", function(newValue, oldValue) {
alert("changed");
}, true);
}
The string doesnt get interolated into the object.
function getTeacher(teacher) {
return $scope.teachers[teacher]
}
scope.$watch(getTeacher(teacher), function() {
//Do stuff
}, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With