AngularJS自定义指令controller和link传参
2017-08-26 13:26
190 查看
指令内部controller与link传参
指令代码:app.directive('myDirective', function() { return { restrict: 'AE', controller: function ($scope, $element, $attrs) { this.test = 1; console.log('controller设置test值: ' + this.test); }, link: function (scope, element, attrs, controller) { console.log('link收到controller的值: ' + controller.test); } }
运行结果:
自定指令中link函数的第四个参数默认为指令内部的controller,如果在该controller内定义一个自身属性,如this.test = 1; link函数就可以直接访问controller的该属性。link函数的controller参数名可以自由定义,只要link函数中该参数名和参数列表中的参数名一致即可。
外部指令controller与link函数传参
现在再定义一个指令:html代码:
... <my-directive> <my-directive2></my-directive2> </my-directive> ...
指令代码:
app.directive('myDirective2', function() { return { restrict: 'AE', require: '^myDirective', link: function (scope, element, attrs, controller) { console.log('myDirective2指令中link函数收到myDirective指令的controller的值: ' + controller.test); } } });
运行结果:
这里切记两点:
1. html中第二个指令必须在第一个指令里面,也是作为它的子节点;
2. 第二个指令要访问外部指令中的 controller时,必须在require中指定要访问的指令名。
require的具体用法请参考:http://blog.csdn.net/victoryzn/article/details/76772068
相关文章推荐
- AngularJs自定义指令详解(6) - controller、require
- angularJS 自定义指令 方法属性:controller 和属性:controllerAs
- AngularJs 指令directive之controller,link,compile
- AngularJs自定义指令详解(5) - link
- angularjs指令(directive)中的controller,compile,link函数有什么不同
- angular 自定义指令 link or controller
- AngularJS之指令中controller与link
- AngularJs中自定义指令directive的controller属性
- angularJS 自定义指令 方法属性:compile、link
- AngularJS之指令中controller与link(十二)
- AngularJs自定义指令详解(5) - link
- angularjs指令link函数参数scope,指令controller依赖注入的$scope,与指令外部controller的$scope的关系
- AngularJS—指令directive之controller,link,compile
- angularJS自定义指令scope代替link
- angularJS 自定义指令 方法属性:controller 和属性:controllerAs
- AngularJs 指令directive之controller,link,compile
- AngularJs自定义指令详解(6) - controller、require
- AngularJS 自定义指令详解 标签: 自定义指令的参数linktemplateUrlscopeAngularJS 自定义指令详解 2016-08-20 15:02 3831人阅读 评论(1)
- [AngularJS] Accessing The View-Model Inside The link() When Using controllerAs
- angularjs不同页面间controller传参方式,使用service封装sessionStorage