一个指令可以继承父级指令中的方法,父级指令把需要暴漏出去的方法放到controller中去,继承方法的指令设置 required:‘^parent’ ;
<!DOCTYPE html> <html> <head> <title>ng1</title> <script type="text/javascript" src="../lib/angular.js"></script> </head> <body ng-app="app"> <div ng-controller="myCtrl"> <dema ng-click="clickWord()" yiji></dema> <dema ng-click="clickWord()" erji></dema> <dema ng-click="clickWord()" dazhao></dema> <dema ng-click="clickWord()" yiji erji dazhao></dema> </div> <script type="text/javascript"> var app = angular.module('app',[]); app.controller('myCtrl',['$scope',function($scope){ $scope.clickWord = function(){ console.log('clickWord') } }]) app.directive('dema',function(){ return{ restrict:'EA', template:'<h1>德玛西亚</h1>', link:function(scope,element,attr){ //操作指令本身的方法 element.addClass('btn btn-default'); element.bind('mouseenter',function(){ console.log(scope.jineng); }) }, scope:{}, controller:function($scope){ //需要被其他指令继承的方法 $scope.jineng = []; this.addfirst = function(){ $scope.jineng.push('第一级技能') } this.addSecond = function(){ $scope.jineng.push('第二级技能') } this.addThird = function(){ $scope.jineng.push('加大招') } } } }) app.directive('yiji',function(){ return{ restrict:'EA', link:function(scope,element,attr,dema){ dema.addfirst(); }, require:'^dema' } }) app.directive('erji',function(){ return{ restrict:'EA', require:'^dema', link:function(scope,element,attr,dema){ dema.addSecond(); } } }) app.directive('dazhao',function(){ return{ restrict:'EA', require:'^dema', link:function(scope,element,attr,dema){ dema.addThird(); } } }) </script> </body> </html>
注:angularJS内置了简化版的jq,即jqLite;所以可以在link,或controller中使用jq的方法;addClass() bind() 等;