本文介绍了角指令如何添加到元素的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是应该做的工作这个片段的方式:

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

//html
<div ng-app="app">
<div ng-controller="AppCtrl">
    <a my-dir ng-repeat="user in users">{{user.name}}</a>
</div>
</div>

//js
var app = angular.module('app', []);
            app.controller("AppCtrl", function ($scope) {
                $scope.users = [{name:'John',id:1},{name:'anonymous'}];
                $scope.fxn = function() {
                    alert('It works');
                };

            })
            app.directive("myDir", function ($compile) {
                return {
                 link:function(scope,el){
                      el.attr('ng-click','fxn()');
                      //$compile(el)(scope); with this the script go mad
                  }
                };
            });

我知道这是对编译阶段
但我不明白的点,这样一个简短的说明会
非常AP preciate。
先谢谢了。

I know it's about the compile phasebut I don't get the point so a short explanation would bevery appreciate.Thanks in advance.

推荐答案

相似的答案:



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

下面是一个plunker:<一href=\"http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=$p$pview\">http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=$p$pview

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);
      };
    }
  };
});


更清洁的解决方案 - 不使用 ngClick 都:

一个plunker:<一href=\"http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=$p$pview\">http://plnkr.co/edit/jY10enUVm31BwvLkDIAO?p=$p$pview

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

这篇关于角指令如何添加到元素的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:01