Angularjs directive

一个人想着一个人 提交于 2020-02-02 06:42:16
.directive('mydir',function(){
      return{
        multiElement: true/false,
        priority: number, //default: 0
        terminal: true/false,
        scope: false/true/{
          myattr: '=attr',
          myattr2: '@str',
          myattr3: '&fun'
        },
        bindToController: true/false,
        controller: function($scope,$element,$attrs,$transclude){
          $transclude([scope], cloneLinkingFn, futureParentElement)
          /*$transclude(function(clone, scope) {
          element.append(clone);
          transcludedContent = clone;
          transclusionScope = scope;
          });*/
        },
        //default: /'?dirName'/
        require: 'dirName'/'?dirName'/'^dirName'/'^^dirName'/'?^dirName'/'?^^dirName',
        controllerAs: 'string',
        restrict: 'ACEM', //default: 'AE'
        templateNamespace: 'html'/'svg'/'math',
        template: 'string'/function(tElement,tAttrs){
          return 'string';
        },
        templateUrl: 'string'/function(tElement,tAttrs){
          return 'string';
        },
        replace: '已被弃用',
        transclude: true/'element',
        compile: function (tElement, tAttrs, transclude) {
          //transclude已被弃用
          return{
            pre: function preLink(scope,iElement,iAttrs,controller){},
            post: function postLink(scope,iElement,iAttrs,controller){}
          }
          //or
          return function (scope,iElement,iAttrs,controller){

          }
        },
        link: function (scope, iElement, iAttrs, controller, transcludeFn) {
          //controller:myselfController/string/array 没有设置require的话默认自己的controller
          //myselfController指指令自己的controller,没有的话设置为undefined
          transclude([scope], cloneLinkingFn, futureParentElement);
        }
      }
    })

priority: 在同一个元素上的指令,数字越大优先级越高,优先级越高controller和pre-link函数越先执行,而post-link则相反。该项不适用不在同一元素上的指令

 

terminal:如果设置为true,那么该指令最后一个执行,优先级低于该指令的指令全都被忽略

 

scope:<mydir attr='variable' attr2='{{str}}' on-ok='foo(a)'></mydir>  

    scope:{ attr:‘=’,   attr2:'@',  onOk:'&'}

 

    '='表示与属性中的变量双向绑定,与父作用域中的变量会相互影响,所以 attr= 后面必须跟一个变量;‘@’表示引用一个字符串之类的表达式;

    ‘&’表示引用一个函数,首先用一个function把他包裹起来,因此onOk=function(a){ foo(a); },如果表达式中包含函数表达式,那么需要将函数写在

    parent scope的function中,比如on-ok = ‘show=false’,直接用 ‘&’引用会报错, ‘show=false’ 只能用@,把他当做字符串处理,因此需要在父作用域中

    $scope.isShow=function(){$scope.show=false},然后on-ok='isShow()'才行

 

bindToController:设置为true的话,此属性会作为scope与controller联系的桥梁

    

controller:

.directive('hello',function(){
      return {
        restrict:'AE',
        template:'<span>hello{{ that.ab }}</span>',
        controller:'parent', //parent是模块上注册的controller
        controllerAs:'that'
      }
})//使用controllerAs的话会将parent作为构造函数实例化,否则就直接使用parent里的$scope

require: 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!