自定义指令

自定义指令有两种方法:

第一种:angular.module('myapp',[],['$compileProvider',function($compileProvider){

  $complieProvider.directive(''指令名',function(){

    return {

    restrict: 'ACEM',

    replace:true,

    transclude:true,

    template:'<div>content<span ng-transclude></span></div>',

  }

})

}])

第二种:angular.module('myapp',[]).directive('指令名',function(){

  return {

    restrict: 'ACEM',

    replace:true,

    transclude:true,

    template:'<div>content<span ng-transclude></span></div>',

    templateUrl:'demo/index.html' //这里的路径是相对angular下的index.html的,模板里的内容可以获取控制器里定义的属性变量

  }

})

指令常用配置属性

 priority //设定指令的优先级,值越大优先级越高

terminal:true//这个属性必须和priority共用,过滤所有比priority值低的指令

 transclude //这个属性可以保留被替换的内容,如在新模板里加上这个就会将原始数据加载到这个div里<div ng-transclude></div>

link
compile
还有一种在当前视图里加载另一个模板的方式
<script type="text/ng-template" id="customTag2">
  在这里写内容,也可以用控制器里的变量,如{{name}}
</script>
<my-tag></my-tag>//这里将用customTag2模板里的内容来替换,必须用分号隔开

angular.module('myapp',[]).directive('指令名:mytag',function(){

  return {

    restrict: 'ACEM',

    replace:true,

    transclude:true,

    templateUrl:'customTag2' //这里的路径是相对angular下的index.html的,模板里的内容可以获取控制器里定义的属性变量

  }

})

原文地址:https://www.cnblogs.com/toward-the-sun/p/4089334.html