Angular directive how to add an attribute to the element?

前端 未结 2 1500
[愿得一人]
[愿得一人] 2020-11-27 04:43

I\'m wondering what\'s the way to do work this snippet:

//html

      
      
2条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 05:22

    A directive which adds another directive to the same element:

    Similar answers:

    • How to get ng-class with $dirty working in a directive?
    • creating a new directive with angularjs

    Here is a plunker: http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

    app.directive("myDir", function($compile) {
      return {
        priority:1001, // compiles first
        terminal:true, // prevent lower priority directives to compile after it
        compile: function(el) {
          el.removeAttr('my-dir'); // necessary to avoid infinite compile loop
          el.attr('ng-click', 'fxn()');
          var fn = $compile(el);
          return function(scope){
            fn(scope);
          };
        }
      };
    });
    

    Much cleaner solution - not to use ngClick at all:

    A plunker: http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=preview

    app.directive("myDir", function($parse) {
      return {
        compile: function(tElm,tAttrs){
          var exp = $parse('fxn()');
          return function (scope,elm){
            elm.bind('click',function(){
              exp(scope);
            });  
          };
        }
      };
    });
    

提交回复
热议问题