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

相關文章
相關標籤/搜索