1.指令 transclude 保留原来的内容 replace 去掉<my-directive>指令
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> <div ng-app="a"> <my-directive><div>这是原来的<p>this is p</p></div></my-directive> </div> <script> var app = angular.module('a', []); app.directive('myDirective', function () { return{ template:'<div>this is directive<div ng-transclude=""></div></div>', transclude:true, replace:true } }); </script>
2.指令绑定函数
<body ng-app="a"> <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> <div ng-controller="ctrl1"> <my-directive>鼠标移上来</my-directive> </div> <!--指令绑定函数 ,借助 link --> <script> var app = angular.module('a', []); app.controller('ctrl1', function ($scope) { $scope.load= function () { console.log("loading.."); } }) app.directive('myDirective', function () { return{ link: function (scope,element,attrs) { element.bind('mouseover', function () { // scope.load(); scope.$apply("load()"); // 两种方式 }) } } }); </script>
3.指令复用,绑定不同函数
<body ng-app="a"> <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> <div ng-controller="ctrl1"> <my-directive howToLoad="load()">鼠标移上来1</my-directive> </div> <div ng-controller="ctrl2"> <my-directive howToLoad="load2()">鼠标移上来2</my-directive> </div> <!--指令复用,绑定不同函数 ,要添加不同属性 howToLoad --> <script> var app = angular.module('a', []); app.controller('ctrl1', function ($scope) { $scope.load= function () { console.log("loading.."); } }) app.controller('ctrl2', function ($scope) { $scope.load2= function () { console.log("loading.22."); } }) app.directive('myDirective', function () { return{ link: function (scope,element,attrs) { element.bind('mouseover', function () { scope.$apply(attrs.howtoload); }) } } }); </script>
4.独立指令 $scope:{} 使每个复用的hello指令不受影响,在第一个hello输入值时,第二个hello不受影响
<body ng-app="a"> <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> <hello></hello><br/> <hello></hello> <script> var app = angular.module('a', []); app.directive('hello', function () { return{ template:'<input type="text" ng-model="name">{{name}}', scope:{} } }) </script>
5.指令scope @
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> 隔离作用域中把 myText同dom中的your-text属性绑定 <div ng-app="a"> <hello url="http://www.baidu.com" your-text="sohu"></hello> </div> <script> var app=angular.module('a',[]); app.directive('hello', function () { return{ template:'<div><a href="{{url}}">{{myText}}</a></div>', replace:true, scope:{ myText:'@yourText', url:'@' } } }) </script>