angularjs中的指令

1、指令与控制器之间的交互:经过指令中的link函数来实现app

<body ng-app="myApp" ng-controller="myCtrl">
    <my-print>鼠标进入触发打印</my-print>

    <script>
        angular.module('myApp',[])
        .controller('myCtrl',function($scope){
            $scope.print=function(){
                console.log('我是打印数据....')
            }
        })
        .directive('myPrint',function(){
            return{
                restrict:'E',
                link:function(scope,element,attrs){
                    element.bind('mouseenter',function(){
                        scope.print();
                    })
                }
            }
        })
    </script>
</body>

2、指令与指令间的交互:函数

<body ng-app="myApp">
    <div>
        <superman strength>动感超人--力量</superman>
    </div>
    <div>
        <superman strength speed>动感超人--力量+敏捷</superman>
    </div>
    <div>
        <superman strength speed light>动感超人--力量+敏捷+发光</superman>
    </div>

    <script>
        var app=angular.module('myApp',[])
        app.directive('superman',function(){
            return{
                restrict:'E',
                scope:{},
                controller:function($scope){
                    $scope.abilities=[];
                    this.addStrength=function(){
                        $scope.abilities.push('strength');
                    };
                    this.addSpeed=function(){
                        $scope.abilities.push('speed');
                    };
                    this.addLight=function(){
                        $scope.abilities.push('light');
                    }
                },
                link:function(scope,element,attrs){
                    element.bind('mouseenter',function(){
                        console.log(scope.abilities);
                    })
                }
            }
        })
        app.directive('strength',function(){
            return{
                require:'^superman',
                link:function(scope,element,attrs,supermanCtrl){
                    supermanCtrl.addStrength();
                }
            }
        })
        app.directive('speed',function(){
            return{
                require:'^superman',
                link:function(scope,element,attrs,supermanCtrl){
                    supermanCtrl.addSpeed();
                }
            }
        })
        app.directive('light',function(){
            return{
                require:'^superman',
                link:function(scope,element,attrs,supermanCtrl){
                    supermanCtrl.addLight();
                }
            }
        })
    </script>
</body>

3、示例说明ui

1.自定义指令下的link函数有四个参数:scope,element,attrs和ctrl(关联ctrl)this

2.require:请求另外的controller,传入当前directive的link 函数中。require须要传入一个directive controller的名称。若是找不到这个名称对应的controller,那么将会抛出一个error。名称能够加入如下前缀:spa

         ? - 不要抛出异常。这使这个依赖变为一个可选项。rest

         ^ - 容许查找父元素的controllercode

3.在上面的示例中<superman></superman>指令中添加的strength speed light其实也是指令,是以属性的方式存在的。blog