[英]$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) 我想在一个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);
}
The string doesnt get interolated into the object. 字符串不会被内置到对象中。
function getTeacher(teacher) {
return $scope.teachers[teacher]
}
scope.$watch(getTeacher(teacher), function() {
//Do stuff
}, true);
Previously, teachers[teacher]
was undefined
because there were no ' '
(quotes) around the teacher
. 以前, teachers[teacher]
undefined
因为teacher
周围没有' '
(引号)。
for (var teacher in $scope.teachers){
$scope.$watch("teachers['"+ teacher +"']", function(newValue, oldValue) {
alert("changed");
}, true);
}
You can't use use an outside value inside a $watch, specially inside a loop. 你不能在$ watch中使用外部值,特别是在循环内部。 Picture it as an interval, if you put an interval or a timeout inside a loop, the value of the variable handled outside the interval ('$scope.teachers[teacher]' in this case) will not be accesible from the inside, or at least will take the last iteration value. 将其描述为间隔,如果在循环内放置间隔或超时,则在间隔之外处理的变量的值(在这种情况下为'$ scope.teachers [teacher]')将无法从内部访问,或者至少会采用最后一次迭代值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.