有时候,自定义的Directive中需要调用controller中的方法,即Directive与controller有一定的耦合度。
比如有如下的一个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);
})
}
})