Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$watch for objects in JSON Angularjs

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);
}
like image 379
Alfonso Mateos Avatar asked Dec 01 '25 06:12

Alfonso Mateos


2 Answers

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);
}
like image 118
Ravi Teja Avatar answered Dec 03 '25 19:12

Ravi Teja


The string doesnt get interolated into the object.

function getTeacher(teacher) {
   return $scope.teachers[teacher]
}

scope.$watch(getTeacher(teacher), function() {
//Do stuff
},  true);
like image 40
Sten Muchow Avatar answered Dec 03 '25 18:12

Sten Muchow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!