var myModule = angular.module(...); myModule.directive('directiveName',function factory(injectables) { var directiveDefinitionObject = { priority: 0,template: '<div></div>',templateUrl: 'directive.html',replace: false,transclude: false,restrict: 'A',scope: false,compile: function compile(tElement,tAttrs,transclude) { return { pre: function preLink(scope,iElement,iAttrs,controller) { ... },post: function postLink(scope,controller) { ... } } },link: function postLink(scope,iAttrs) { ... } }; return directiveDefinitionObject; });
<my-directive><a href="http://google.com">Click me to go to Google</a></my-directive> <p my-directive=""><a href="http://google.com">Click me to go to Google</a></p>
- E 元素方式 <my-directive></my-directive>
- A 属性方式 <div my-directive="exp"> </div>
- C 类方式 <div class="my-directive: exp;"></div>
- M 注释方式 <!-- directive: my-directive exp -->
templateUrl : "../myTemplate.html" // 或者动态获取 templateUrl: function(element,attrs) { return attrs.templateUrl || '../../uib/template/alert/alert.html'; },
<a href="http://google.com">Click me to go to Google</a> <a href="http://google.com" my-directive="">Click me to go to Google</a>
<body ng-app="myApp"> <div ng-controller="TestCtrl"> <div a abc="here" xx="{{ a }}" c="ccc"></div> </div> </body>
angular.module('myApp',[]) .controller('TestCtrl',function($scope){ $scope.a = '123'; $scope.here = 'here ~~'; }) .directive('a',function(){ var func = function(element,attrs,link){ return function(scope){ /** 输出结果 a: "here" b: "123" c: "ccc" d: "ccc" e: "here ~~ */ console.log(scope); }; }; return { restrict: 'A',compile: func,@H_502_0@ // a 找到属性名为abc,其值为here
// b 找到属性名为xx,其值为{{a}} 接着找$scope.a 存在,其值为 123
// c @attrName 没有写attrName,默认取自己的值,等价于@c,找到属性c,其值为ccc
// d 如上
// e '=abc' 把属性abc的值当作scope的属性名。 这里存在属性abc,其值为here。存在$scope.here。最终值为'here ~~'
// 若改为abc={{ here }} 效果跟 b: '@xx '一样
scope: {a: '@abc',b: '@xx',c: '@',d: '@c',e: '=abc'} }; });