angularJS directive中的controller和link function辨析
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了angularJS directive中的controller和link function辨析,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1576字,纯文字阅读大概需要3分钟。
内容图文
在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被编译的时间顺序:
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/
原文:http://www.cnblogs.com/kidsitcn/p/4850574.html
内容总结
以上是互联网集市为您收集整理的angularJS directive中的controller和link function辨析全部内容,希望文章能够帮你解决angularJS directive中的controller和link function辨析所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。