Angular 指令如何向元素添加属性? [英] Angular directive how to add an attribute to the element?

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

问题描述

我想知道如何处理此代码段:

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

//jsvar app = angular.module('app', []);app.controller("AppCtrl", function ($scope) {$scope.users = [{name:'John',id:1},{name:'anonymous'}];$scope.fxn = 函数(){alert('它有效');};})app.directive("myDir", function ($compile) {返回 {链接:功能(范围,EL){el.attr('ng-click','fxn()');//$compile(el)(scope);有了这个,脚本发疯了}};});

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

解决方案

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

类似的答案:

这是一个plunker:http://plnkr.co/edit/ziU8d826WF6SwQllHHQq?p=preview

app.directive("myDir", function($compile) {返回 {priority:1001,//先编译terminal:true,//阻止低优先级的指令在它之后编译编译:函数(el){el.removeAttr('我的目录');//避免无限编译循环所必需的el.attr('ng-click', 'fxn()');var fn = $compile(el);返回函数(范围){fn(范围);};}};});

<小时>

更简洁的解决方案 - 根本不使用 ngClick:

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

app.directive("myDir", function($parse) {返回 {编译:函数(tElm,tAttrs){var exp = $parse('fxn()');返回函数(范围,榆树){elm.bind('点击',function(){exp(范围);});};}};});

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

I know it's about the compile phase but I don't get the point so a short explanation would be very appreciate.

A directive which adds another directive to the same element:

Similar answers:

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

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

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆