如何观看对象属性?

CHS*_*CHS 4 angularjs angularjs-directive

我想要一个可以像这样使用的属性指令:

<div my-dir="{items:m.items, type:'0'}"></div>
Run Code Online (Sandbox Code Playgroud)

在我的指令中,我可以把它变成一个像这样的对象:

function (scope, element, attributes, modelController)
{
   var ops = $.extend({}, scope.$eval(attributes.myDir));
}
Run Code Online (Sandbox Code Playgroud)

现在说m.items是一个数组.在某个地方,一个ajax调用用一个新的替换数组.我想留意这个.

如何查看m.items或为属性中的items属性键入的内容?表达式应该是什么?

Ada*_*dam 6

你应该能够使用范围.$ watch来观察属性.当任何值发生更改时,Angular将调用整个对象的回调.

function(scope, elem, attrs) {
  scope.$watch(attrs.myDir, function(val) {
    // Do something with the new value, val.
  }, true);
}
Run Code Online (Sandbox Code Playgroud)

http://plnkr.co/edit/JBGqW8uFzh1eJ1Ppq3fT

无论何时模型更改(通过在输入中键入内容),指令都会更新$ watch中的元素html.

编辑我的答案:你想要包含true作为比较对象值而不是引用的最后一个参数.否则你将运行digest超过10次并获得异常.