2016-09-27 35 views
2

我想在指令中創建一個指向特定部分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); 
} 
+0

你想達到什麼做創建指令裏面的手錶,請說清楚,並與您的代碼plunkr將有助於解決您的問題 –

+0

我要做的就是調用highcharts插件: 新Highcharts.chart(老師+「_id」,chartoptions); 但在這種情況下,我不認爲它是相關的,問題是它永遠不會進入手錶 –

+1

'JsonObject.teacher'是'undefined'因此您可以使用'JsonObject.profs'或'teacher.profs' –

回答

1

此前,teachers[teacher]undefined,因爲沒有' '(引號)的teacher周圍 。

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

非常感謝,這就是我一直在尋找的。 但是,如果有人(像我一樣)有新問題,並且有同樣的問題,那麼知道這一點很重要: 1)不可能在手錶內存取變量「teacher」,因爲該值可能已更改爲執行手錶的時間,請使用newValue,oldValue代替 2)不要在手錶內部創建調試器或斷點,因爲它會彈出一個錯誤:主執行程序等待手錶永不終止(我認爲)。而是使用跟蹤來進行調試,如console.log() –

1

該字符串不會相互連接到對象中。

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

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