天天看點

AngularJs 指令directive之controller,link,compile

關于自定義指令的命名,你可以随便怎麼起名字都行,官方是推薦用[命名空間-指令名稱]這樣的方式,像ng-controller。不過你可千萬不要用 ng-字首了,防止與系統自帶的指令重名。另外一個需知道的地方,指令命名時用駝峰規則,使用時用-分割各單詞。如:定義mydirective,使用時 像這樣:<my-directive>。

這裡列出directive的合法命名:

ng:bind

ng-bind

ng_bind

x-ng-bind

data-ng-bind

我是教師,在建立試題輸入分數的時候應該隻能輸入數字才對,輸入其他内容是不合法的,而且我希望這個分數是1~10之間的數字。能否隻在輸入框上加一個屬性.我們定義一個叫做fractionnum的指令如下

AngularJs 指令directive之controller,link,compile

app.directive('fractionnum',function(){  

    return {  

        link : function(scope, elements, attrs, controller){  

            elements[0].onkeyup = function(){  

                if(isnan(this.value) || this.value<1 || this.value>10){  

                    this.style.bordercolor = 'red';  

                }  

                else{  

                    this.style.bordercolor = '';  

            };  

        }  

    };  

});  

link的值是一個函數,用來定義指令的行為。從傳入的參數中可以擷取到目前元素,我們便可以拿目前元素開刀了。我在此處監聽目前元素的keyup事件,擷取元素的值,如果不是1~10之間的數字,則把輸入框的邊框顔色變為紅色。這下這個指令就可以工作了。定義好的指令就可以在模闆中使用了,使用方法如下:

AngularJs 指令directive之controller,link,compile

分數:<input type="text" ng-model="question.fraction" fraction-num /><br />  

controller,link,compile有什麼不同

AngularJs 指令directive之controller,link,compile

//directives.js增加exampledirective  

phonecatdirectives.directive('exampledirective', function() {  

        restrict: 'e',  

        template: '<p>hello {{number}}!</p>',  

        controller: function($scope, $element){  

            $scope.number = $scope.number + "22222 ";  

        },  

        //controlleras:'mycontroller',  

        link: function(scope, el, attr) {  

            scope.number = scope.number + "33333 ";  

        compile: function(element, attributes) {  

            return {  

                pre: function prelink(scope, element, attributes) {  

                    scope.number = scope.number + "44444 ";  

                },  

                post: function postlink(scope, element, attributes) {  

                    scope.number = scope.number + "55555 ";  

    }  

//controller.js添加  

dtcontrollers.controller('directive2',['$scope',  

    function($scope) {  

        $scope.number = '1111 ';  

]);  

//html  

<body ng-app="phonecatapp">  

    <div ng-controller="directive2">  

        <example-directive></example-directive>  

    </div>  

</body>  

 運作結果:

AngularJs 指令directive之controller,link,compile

hello 1111 22222 44444 55555 !    

 由結果可以看出來,controller先運作,compile後運作,link不運作(link就是compile中的postlink)。将上例中的compile注釋掉運作結果:

AngularJs 指令directive之controller,link,compile

hello 1111 22222 33333 !    

 由結果可以看出來,controller先運作,link後運作,link和compile不相容。compile改變dom,link事件的觸發和綁定