AngularJS自定义Directive与controller的交互
2015-12-28 22:28
567 查看
有时候,自定义的Directive中需要调用controller中的方法,即Directive与controller有一定的耦合度。
比如有如下的一个controller:
现在自定义一个Direcitve,需要调用MyCtrl这个controller中的load方法。
页面这样调用:
如果想调用MyCtrl中的其它方法呢?这时候就需要更改direcitve中的编码。由此可见在directive以硬编码的方法是调用controller中的方法是不太合理的。
那么把变化的可能性放在页面上会怎样呢?
给enter一个属性值,该属性值表示调用哪个方法。
这样,总比在directive中硬编码要灵活一些。
directive相应改成这样:
可是,以上写法还不是最合理的,因为在调用上下文的$apply方法的时候传入的实参也是字符串。
别忘了,link函数中还有一个形参attrs,通过这个可以获取任意属性值。
比如有如下的一个controller:
app.controller('MyCtrl',function($scope){ $scope.load = function(){ console.log('loading more...') } });
现在自定义一个Direcitve,需要调用MyCtrl这个controller中的load方法。
app.directive('enter', function(){ return function($scope, ele, attrs){ ele.bind('mouseenter', function(){ $scope.load(); }) } })
页面这样调用:
<div ng-controller="MyCtrl"> <div enter>enter to load more</div> </div>
如果想调用MyCtrl中的其它方法呢?这时候就需要更改direcitve中的编码。由此可见在directive以硬编码的方法是调用controller中的方法是不太合理的。
那么把变化的可能性放在页面上会怎样呢?
给enter一个属性值,该属性值表示调用哪个方法。
<div ng-controller="MyCtrl"> <div enter="load()">enter to load more</div> </div>
这样,总比在directive中硬编码要灵活一些。
directive相应改成这样:
app.directive('enter', function(){ return function($scope, ele, attrs){ ele.bind('mouseenter', function(){ $scope.$apply('load()'); }) } })
可是,以上写法还不是最合理的,因为在调用上下文的$apply方法的时候传入的实参也是字符串。
别忘了,link函数中还有一个形参attrs,通过这个可以获取任意属性值。
app.directive('enter', function(){ return function($scope, ele, attrs){ ele.bind('mouseenter', function(){ $scope.$apply(attrs.enter); }) } })
相关文章推荐
- AngularJS 控制器函数
- AngularJS 控制器属性
- AngularJS 控制器
- TypeScript 5 Angular 2
- AngularJS自定义Directive不一定返回对象
- 使用 AngularJS 和 Electron 构建桌面应用
- angularjs ui-grid如何动态设置行高
- angularjs中的service
- 成也绑定,败也绑定,AngularJs雄霸天下
- angularjs的过滤器
- angularjs中的promise
- 形象的讲解angular中的$q与promise
- 让AngularJS的controllers之间共享数据
- Angularjs interceptor
- Angularjs注入拦截器实现Loading效果
- angular学习日志08 ng-show ng-hide
- AngularJS进行性能调优的7个建议
- 浅析AngularJS Filter用法
- 详解AngularJS Filter(过滤器)用法
- 详解AngularJS中自定义过滤器