为什么我们需要Angular指令的链接函数

时间:2015-11-27 07:23:48

标签: javascript angularjs angularjs-directive

我搜索并阅读了很多但仍感到困惑。

问题是,如果我有如下指令

.directive('someDirective',function(){
    return{
        scope:{},
        bindToController:{
            prop:"="
        },
        templateUrl:'myTemplate.html',
        controller:'directiveController'
    }
})

.controller('directiveController',function(){
    //Do controller stuff
})

为什么我需要链接功能?我几乎可以将整个DOM绑定到控制器以传递数据。(是的,我知道当我们想要根据角度文档公开API函数时应该使用控制器)。当bindToController不存在时,预角度1.2仍然有意义。

我已经读过有pre和post方法,这是我们应该做的事情,比如附加元素等等。但是我很困惑,为什么我会在我将它添加到“myTemplate.html”时附加内容”

请你给我们一些相关的例子,我们应该使用链接而不是控制器,有什么区别。

2 个答案:

答案 0 :(得分:1)

简短回答:

初始化控制器时,不会呈现指令的DOM。如果你想设置监听器('$ watch'),你需要在DOM渲染后执行的链接功能。

答案很长: https://docs.angularjs.org/api/ng/service/$compile

答案 1 :(得分:0)

我以前没有机会使用前连接或后链接功能,但是我们在框架中一直使用链接功能来获取窗口小部件的特定实例,然后使用它做一些事情。

我们框架中的一个小部件是网格。在网格内部,我们为用户提供了编辑单元格内容的功能。

我们框架的用户可以在他们的标记中添加这样的属性:

<sg-grid editable="true"></sg-grid>

然后我们使用链接函数中的attrs参数来查找此属性:

angular.module('sg.grid').directive('sgGrid', [

   restrict: 'E', // this is an element directive
   scope: {
      editable: @editable // each grid has its own, isolated scope
   },
   template: '<div class="sg-grid" ng-click="someFunction()"></div>', // we also add behaviour to the widget using events that are added to scope in the link()

   link: function (scope, elm, attrs, ctrls) {

      if (!_.isUndefined(attrs.editable)) { // underscore.js is used to check if it is defined

         if(attrs.editable === 'true' {
            addEditFunctionalityToCell();
         }

         addEditFunctionalityToCell() {
            ...
         }             
      }
      scope.someFunction = function() { ... } // this is bound to ng-click in the template
   }
   ...
]);
相关问题