【问题标题】:Angular directive how to add an attribute to the element?Angular指令如何向元素添加属性?
【发布时间】:2014-03-08 10:00:25
【问题描述】:

我想知道这个 sn-p 的工作方式是什么:

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

我知道这是关于编译阶段 但我不明白这一点,所以简短的解释是 非常感谢。

【问题讨论】:

标签: angularjs angularjs-directive


【解决方案1】:

你可以试试这个:

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

<script>
var app = angular.module('app', []);

function AppCtrl($scope) {
        $scope.users = [{ name: 'John', id: 1 }, { name: 'anonymous' }];
        $scope.fxn = function () {
            alert('It works');
        };
    }

app.directive("myDir", function ($compile) {
    return {
        scope: {ngClick: '='}
    };
});
</script>

【讨论】:

  • 属性应该是动态添加的。不是来自模板
【解决方案2】:

将另一个指令添加到同一元素的指令:

类似的答案:

这里是一个笨蛋: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

一个笨蛋: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);
        });  
      };
    }
  };
});

【讨论】:

  • 知道为什么在使用 ng-repeat 并在指令的控制器上调用函数时这不起作用吗?我已经修改了你的 plunker 以表明我的意思。请注意,单击时调用的方法现在位于指令控制器上。另请注意,未嵌套在 ng-repeat 中的“This works”链接有效,而其他链接无效:plnkr.co/edit/Y4ADmznnDCZvuxJrcZQ0?p=preview
  • 删除“my-dir”会弄乱我的 CSS 规范。有解决方法吗?谢谢
  • 你可以将 my-dir-unloaded attr 替换为 my-dir(或 my-dir-loaded),这样 CSS 就可以工作,而指令不会进入无限循环(只是猜测,没有不要尝试)
  • @Dinesh var fn = $compile(el, null, 1001); 并保持my-dir 属性不变。
  • 在当前正在编译的同一元素上简单地调用 $compile() 是不正确的,它会重新编译恰好具有更高优先级的其他无关指令。
猜你喜欢
  • 2013-10-17
  • 2019-03-12
  • 2023-03-24
  • 1970-01-01
  • 2018-08-26
  • 1970-01-01
  • 2018-06-21
  • 2017-02-03
  • 1970-01-01
相关资源
最近更新 更多