简体   繁体   English

为什么指令没有执行

[英]Why is the directive not executed

I am wondering why the directive my-dir is not executed after I click the items. 我想知道为什么我单击项目后没有执行指令my-dir It is executed when the page is loaded and on a finish-editing event (in fact the child divs represent ng-grid cells, that's why there exists such an event) 它在页面加载和完成编辑事件时执行(事实上,子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>

The Controller and directive are defined roughly as follows: 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
           }        
       };       
    };
 });

Thanks in advance! 提前致谢! (Note that I have written the code only for this question, it is a model of the original, but it hopefully illustrates my problem) (注意,我只为这个问题编写了代码,它是原始的模型,但它希望能说明我的问题)

The link function in the directive is only called once (when the scope is being linked to the DOM). 指令中的link函数只调用一次(当范围链接到DOM时)。 This is during the link phase. 这是在链接阶段。

So the clause: 所以条款:

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

will only by executed once per directive, at the moment. 目前只能按指令执行一次。

If you want to watch for changes in a value, you would need to set that up in the directive: 如果要监视值的更改,则需要在指令中进行设置:

   link: function(scope, element, attr){

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

As Davin Tryon already mentioned link is executed only once so, you either have to attach a $watch / $watchCollection or attach a click handler to handle changes 由于Davin Tryon已经提到link只执行一次,你要么必须附加$watch / $watchCollection或附加一个点击处理程序来处理更改

JSFiddle 的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);
    }
  };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM