$在JSON Angularjs中观察对象

时间:2016-09-27 09:39:07

标签: javascript angularjs json watch

我想在一个json对象的特定部分的指令中创建一个$ 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);
}

3 个答案:

答案 0 :(得分:1)

字符串不会被内置到对象中。

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

scope.$watch(getTeacher(teacher), function() {
//Do stuff
},  true);

答案 1 :(得分:1)

以前,teachers[teacher]undefined,因为没有' '(引号) 围绕teacher

for (var teacher in $scope.teachers){
    $scope.$watch("teachers['"+ teacher +"']", function(newValue, oldValue) {
      alert("changed");
   }, true);
}

答案 2 :(得分:1)

不能在$ watch内部使用外部值,尤其是在循环内部。将其描述为一个间隔,如果您将一个间隔或超时放入循环内,则从内部无法访问在该间隔之外处理的变量的值(在这种情况下为'$ scope.teachers [teacher]'),或者至少会取最后的迭代值。