zoukankan      html  css  js  c++  java
  • AngularJS自定义Directive与controller的交互

    有时候,自定义的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);
            })
        }
    })
  • 相关阅读:
    第一篇:GCD的使用
    第一篇:线程的安全
    内存问题
    第一篇:多线程的概念
    第一篇:NSOperation的概念
    存储问题
    第一篇:NSTread线程的创建
    第一篇:多线程使用
    遍历所有表,取每个表的MAXID更新到ID控制表
    <转载>SQL查询数据库各表所占空间
  • 原文地址:https://www.cnblogs.com/darrenji/p/5084245.html
Copyright © 2011-2022 走看看