AngularJS 自定義指令
transclude:當元素標簽需要嵌套時使用,與ng-transclude配合使用。默認值為false不能使用嵌套,true為可以使用嵌套。在哪個標簽上使用ng-transclude就在哪個標簽內進行嵌套。 
代碼示例:(將hello、hi標簽進行替換同時span標簽嵌套div內)
<script type="text/javascript">  var m = angular.module('myApp',[]);  m.directive('hello',function(){    return{      restrict:'E',      replace:true,      transclude:true,      template:'<div>hello angular<h1 ng-transclude></h1></div>'    };  });  m.directive('hi',function(){    return{      restrict:'E',      replace:true,      template:'<span>hi angular</span>'    };  });  m.controller('Aaa',['$scope',function($scope){    $scope.name='hello';  }]);  </script><body ng-controller="Aaa">  <hello>    <hi></hi>  </hello></body>頁面結果展示: 

在自定義指令當中controller與link的區別: 
link是指DOM操作,操作也是針對當前標簽 
controller是多調用性的數據共享,指令與指令間進行交互時也可以設置一些方法數據,在其他標簽中也可以調用
require:從外部引入數據,參數為被引入的指令,被引入的指令需要在引入指令的身上。 
》^:是指被引入的指令是引入指令的父級 
》?:兼容錯誤 
代碼示例:
  <script type="text/javascript">  var m = angular.module('myApp',[]);  m.directive('hello',function(){    return{      restrict:'E',      replace:true,      transclude:true,      controller:function($scope){        //$scope.name='miaov';只能在該標簽中使用        this.name = 'miaov';//可以在其他標簽中調用      },      template:'<div>hello angular<h1 ng-transclude></h1></div>'    };  });  m.directive('hi',function(){    return{      restrict:'E',      replace:true,      require:'?^hello',//從外部引入指令,參數為被引入的標簽      link:function($scope,element,attr,reController){        console.log(reController.name);      },      template:'<span>hi angular</span>'    };  });  m.controller('Aaa',['$scope',function($scope){    $scope.name='hello';  }]);  </script><body ng-controller="Aaa">  <hello>    <hi></hi>  </hello></body>頁面結果展示: 

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答