AngularJS自定义Directive与controller的交互

 

有时候,自定义的Directive中须要调用controller中的方法,即Directive与controller有必定的耦合度。

好比有以下的一个controller:app

 

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一个属性值,该属性值表示调用哪一个方法。

spa

  <div ng-controller="MyCtrl">
    <div enter="load()">enter to load more</div>
  </div>
  

 

这样,总比在directive中硬编码要灵活一些。

directive相应改为这样:code

 

app.directive('enter', function(){
    return function($scope, ele, attrs){
        ele.bind('mouseenter', function(){
            $scope.$apply('load()');
        })
    }
})

 

但是,以上写法还不是最合理的,由于在调用上下文的$apply方法的时候传入的实参也是字符串。

别忘了,link函数中还有一个形参attrs,经过这个能够获取任意属性值。blog

 

app.directive('enter', function(){
    return function($scope, ele, attrs){
        ele.bind('mouseenter', function(){
            $scope.$apply(attrs.enter);
        })
    }
})
相关文章
相关标签/搜索