Angular中Directive总结
参考:http://www.zouyesheng.com/angular.html Directive指令 个人理解增强复用性。 操作dom最好放到指令中不要放到controller中。 定义指令的写法模板 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; }); 由上可知,定义指令,需要返回一个对象。对象中包含很多属性如restrict,replace等。下面根据例子介绍每个属性的用法。 例1 See the Pen Directive/1 Basic by finley (@mafeifan ) on CodePen. 生成的html为 <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> 参数restrict:个人理解指令的使用方式。可选值EACM。分别代表element,attribute,class和comment。
参数template:要替换的内容。 参数templateUrl:从指定的url读模版内容,如果内容很长或者需要复用就用这个参数吧。比如我们可以写成 templateUrl : "../myTemplate.html" // 或者动态获取 templateUrl: function(element,attrs) { return attrs.templateUrl || '../../uib/template/alert/alert.html'; }, 参数replace:是否使用模板内容替换掉整个节点, true 替换整个节点, false 替换节点内容。如例1,若replace为true。则生成的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> 参数link: 例2 link方法 See the Pen Directive/2 link by finley (@mafeifan ) on CodePen. 参数scope:绑定策略 参数link和compile。分别代表编译和链接。 例3 绑定 如下TestCtrl里div元素有4个属性。a,abc,xx,c <body ng-app="myApp"> <div ng-controller="TestCtrl"> <div a abc="here" xx="{{ a }}" c="ccc"></div> </div> </body> JS 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, // a 找到属性名为abc,其值为here scope: {a: '@abc',b: '@xx',c: '@',d: '@c',e: '=abc'} }; });
例4 transclude 方法 See the Pen NG Directive学习4 transclude by finley (@mafeifan) on CodePen. name priority terminalcontrollerrequiretransclude (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |