有時候,自定義的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); }) } })