为什么指令没有执行

时间:2014-03-12 16:40:33

标签: javascript angularjs

我想知道为什么在点击项目后没有执行指令my-dir。它是在加载页面和完成编辑事件时执行的(实际上子div代表ng-grid个单元格,这就是存在这样一个事件的原因)

<div ng-controller="Cntl">
    <div ng-click="select(item1)" my-directive="item1"></div>
    <div ng-click="select(item2)" my-directive="item2"></div>
    <div ng-click="select(item3)" my-directive="item3"></div>
</div>

Controller和指令大致定义如下:

app.controller('Cntl',function($scope, ...){
    $scope.highlightedItems = {item1:true, item2:false, item3:false};
    $scope.select = function(item){
        // basically set the value of the property in $scope.highlightedItems to true
        // the structure of the items is a bit more sophisticated though
        // but it doesnt matter here
    };
    $scope.is_highlighted = function(item){ // checks if $scope.highlightedItems is true or false for item 
    };   
};
app.directive('myDirective', function(){
   return {
       link: function(scope, element, attr){
          if(scope.is_highlighted(attr.myDirective)){
              // do something
           }        
       };       
    };
 });

提前致谢! (请注意,我只为这个问题编写了代码,它是原始模型,但它有望说明我的问题)

2 个答案:

答案 0 :(得分:2)

指令中的link函数只调用一次(当作用域链接到DOM时)。这是在链接阶段。

所以条款:

   if(scope.is_highlighted(attr.myDirective)){
      // do something
   } 

目前只能按指令执行一次。

如果要监视值的更改,则需要在指令中进行设置:

   link: function(scope, element, attr){

      scope.$watch('highlightedItems', function(value) {
          if(scope.is_highlighted(attr.myDirective)){
              // do something
          }
      }, true);        
   }; 

答案 1 :(得分:0)

由于已提及Davin Tryon link只执行一次,因此您必须附加$watch / $watchCollection或附加点击处理程序来处理更改

JSFiddle

app.directive('myDirective', function () {
  return {
    link: function (scope, element, attr) {
      var listener = function () {
        if (scope.is_highlighted(attr.myDirective)) {
          // do something
        }
      };
      listener();
      element.on('click', listener);
    }
  };
});
相关问题