AngularJS —— 創(chuàng)建自定義的指令

除了 AngularJS 內(nèi)置的指令外,我們還可以創(chuàng)建自定義指令。
你可以使用 .directive 函數(shù)來添加自定義的指令。
要調(diào)用自定義指令,HTML 元素上需要添加自定義指令名。
使用駝峰法來命名一個指令, runoobDirective, 但在使用它時需要以 - 分割, runoob-directive:

AngularJS 實例
<body ng-app="myApp">

<runoob-directive></runoob-directive>

<script>
var app = angular.module("myApp", []);
app.directive("runoobDirective", function() {
    return {
        template : "<h1>自定義指令!</h1>"
    };
});
</script>

</body>

你可以通過以下方式來調(diào)用指令:

  • 元素名
  • 屬性
  • 類名
  • 注釋

限制使用:你可以限制你的指令只能通過特定的方式來調(diào)用。

restrict 值可以是以下幾種:

  • E 作為元素名使用
  • A 作為屬性使用
  • C 作為類名使用
  • M 作為注釋使用
    restrict 默認(rèn)值為 EA, 即可以通過元素名和屬性名來調(diào)用指令。

angular自定義指令的兩種寫法:

上面這種,感覺更清晰明確一點。
// angular.module('MyApp',[])
// .directive('zl1',zl1)
// .controller('con1',['$scope',func1]);
//
// function zl1(){
//   var directive={
//     restrict:'AEC',
//     template:'this is the it-first directive',
//   };
//   return directive;
// };
//
// function func1($scope){
//   $scope.name="alice";
// }

//這是教程里類似的寫法
angular.module('myApp',[]).directive('zl1',[ function(){
  return {
    restrict:'AE',
    template:'thirective',
    link:function($scope,elm,attr,controller){
      console.log("這是link");
    },
    controller:function($scope,$element,$attrs){
      console.log("這是con");
    }
  };
}]).controller('Con1',['$scope',function($scope){
  $scope.name="aliceqqq";
}]);

還有指令配置項的:link controller等在項目運用中有遇到過:

angular.module('myApp', []).directive('first', [ function(){
    return {
        // scope: false, // 默認(rèn)值,共享父級作用域
        // controller: function($scope, $element, $attrs, $transclude) {},
        restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment
        template: 'first name:{{name}}',
    };
}]).directive('second', [ function(){
    return {
        scope: true, // 繼承父級作用域并創(chuàng)建指令自己的作用域
        // controller: function($scope, $element, $attrs, $transclude) {},
        restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment
        //當(dāng)修改這里的name時,second會在自己的作用域中新建一個name變量,與父級作用域中的
        // name相對獨立,所以再修改父級中的name對second中的name就不會有影響了
        template: 'second name:{{name}}',
    };
}]).directive('third', [ function(){
    return {
        scope: {}, // 創(chuàng)建指令自己的獨立作用域,與父級毫無關(guān)系
        // controller: function($scope, $element, $attrs, $transclude) {},
        restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment
        template: 'third name:{{name}}',
    };
}])
.controller('DirectiveController', ['$scope', function($scope){
    $scope.name="mike";
}]);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容