AngularJS自定义Directive与controller的交互

本文探讨了在AngularJS中,如何使自定义的Directive调用Controller中的方法,避免硬编码,实现更灵活的调用方式。通过示例展示了如何使用属性传递方法名,以及在Directive中动态调用这些方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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

 

转载于:https://www.cnblogs.com/darrenji/p/5084245.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值