angularJS directive中的controller和link function辨析

在angularJS中,你有一系列的view,负责将数据渲染给用户;你有一些controller,负责管理scope(viewmodel)behavior(scope定义)给到view;你有一些directive,负责将user interaction和$scope behavious link起来。但是还有一样东西: a directive controller.这个directive controller子一个directive的context中定义,但是它又可以被injected到其他的directives中作为一种便利化inter-directive communication的方法。

angularJS中directive应该是最重要最强大的了,在ddo中,有两个地方可以引入自定义的功能,一个是controller属性,一个是link属性,directive的这两个属性到底有什么区别呢?我们的代码到底应该放到directive的controller还是link属性中去呢?

问一下自己:我希望这段代码什么时间点去运行呢?对这个问题的回答决定了你应该讲代码放到哪里:

  • 在compilation之前运行? - 放到controller属性中去
  • 希望暴露一个API给其他directives? -放到controller属性中去定义API
  • 在compilation之后运行? - 放到link属性中

angular在compile,link,controller被编译的时间顺序:

复制代码
angular.module('compilation', [])

.directive('logCompile', function($rootScope) {
  $rootScope.log = "";

  return {
    controller: function($scope, $attrs) {
      $rootScope.log = $rootScope.log + ($attrs.logCompile + ' (controller)\n');
    },
    compile: function compile(element, attributes) {
      $rootScope.log = $rootScope.log + (attributes.logCompile + ' (compile)\n');
      return {
        pre: function preLink(scope, element, attributes) {
          $rootScope.log = $rootScope.log + (attributes.logCompile + ' (pre-link)\n');
        },
        post: function postLink(scope, element, attributes) {
          element.prepend(attributes.logCompile);
          $rootScope.log = $rootScope.log + (attributes.logCompile + ' (post-link)\n');
        }
      };
    }
  };
})

.directive('terminate', function() {
  return {
    terminal: true
  };
});
复制代码

http://jasonmore.net/angular-js-directives-difference-controller-link/

 

posted @   世有因果知因求果  阅读(2935)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示