angularJS directive中的controller和link function辨析
2015-10-01 00:29
501 查看
在angularJS中,你有一系列的view,负责将数据渲染给用户;你有一些controller,负责管理$scope(view model)并且暴露相关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被编译的时间顺序:
![](http://images2015.cnblogs.com/blog/737565/201510/737565-20151001002709074-814914765.png)
http://jasonmore.net/angular-js-directives-difference-controller-link/
angularJS中directive应该是最重要最强大的了,在ddo中,有两个地方可以引入自定义的功能,一个是controller属性,一个是link属性,directive的这两个属性到底有什么区别呢?我们的代码到底应该放到directive的controller还是link属性中去呢?
问一下自己:我希望这段代码什么时间点去运行呢?对这个问题的回答决定了你应该讲代码放到哪里:
在compilation之前运行? - 放到controller属性中去
希望暴露一个API给其他directives? -放到controller属性中去定义API
在compilation之后运行? - 放到link属性中
angular在compile,link,controller被编译的时间顺序:
![](http://images2015.cnblogs.com/blog/737565/201510/737565-20151001002709074-814914765.png)
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/
相关文章推荐
- angular实用手册
- 自定义angularjs分页控件
- angularjs指令
- angular之显示注入声明
- angular之$compile
- angular中的异常机制与异常之外的处理
- angularjs 未整理--笔记--简单使用和简介
- angular-translate
- 学习笔记-AngularJs(八)
- AngularJS 官方案例:angular-phonecat
- angular之modal实现
- angular之$provide
- angular之$injector
- 前端见微知著AngularJS备忘篇:温故而知新,可以为师矣
- [RxJS + AngularJS] Sync Requests with RxJS and Angular
- AngularJS之延迟加载html template
- angularjs
- AngularJs学习笔记一
- AngularJs学习笔记二
- AngularJS报错:[$compile:tpload]