AngularJS —— 創建自定義的指令

除了 AngularJS 內置的指令外,我們還可以創建自定義指令。
你可以使用 .directive 函數來添加自定義的指令。
要調用自定義指令,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>

你可以通過以下方式來調用指令:

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

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

restrict 值可以是以下幾種:

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

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, // 默認值,共享父級作用域
        // 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, // 繼承父級作用域并創建指令自己的作用域
        // controller: function($scope, $element, $attrs, $transclude) {},
        restrict: 'AE', // E = Element, A = Attribute, C = Class, M = Comment
        //當修改這里的name時,second會在自己的作用域中新建一個name變量,與父級作用域中的
        // name相對獨立,所以再修改父級中的name對second中的name就不會有影響了
        template: 'second name:{{name}}',
    };
}]).directive('third', [ function(){
    return {
        scope: {}, // 創建指令自己的獨立作用域,與父級毫無關系
        // 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";
}]);
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容