2014-11-04 108 views
1

我的指令具有隔离范围,它从封闭控制器接收对象作为属性。

app.directive('details', function() { 
     return { 
      restrict : 'E', 
      scope : { 
       device : '=device', 
       . 
       . 
       . 
      }, 
      templateUrl : '/details.html', 
      link : function(scope, element, attrs) { 
       attrs.$observe('device', function(value) { 
       ... 
       }); 
      } 
     }; 
    }); 

而在HTML:

<details device='ctrlAlias.device' ...> 

我读的地方,如果我想为您在属性的变化,我需要使用$observe功能。但是,我看到的大多数示例仅在原始值上使用$observe

我不知道我将如何$observedevice的属性,说attrs.$observedevice.exist(一个布尔值)和device.id(字符串)?

回答

3

您应该使用$watch

注册了一个侦听器回调要执行每当watchExpression变化。

然而,$observe是这样的方法在Attributes对象

观察内插属性。

代码

scope.$watch(function() { 
    return scope.device 
}, function(newValue, oldValue) {  
}, true); 

更多详情,请访问AngularJS : Difference between the $observe and $watch methods

+0

看到这篇文章了解'$ watch'和'$ observe'之间区别的更多细节。 http://stackoverflow.com/questions/14876112/difference-between-the-observe-and-watch-methods – morloch 2014-11-04 11:01:35

+0

@Satpal我编写了'function(newValue,oldValue){if(typeof oldValue ===“undefined”)&& (newValue.exist == true){...}}'但我得到属性未定义。 – menorah84 2014-11-04 11:21:05

+0

@ menorah84,期望值'ctrlAlias.device'是什么? – Satpal 2014-11-04 11:30:16