加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – Angular指令如何添加一个属性到元素?

发布时间:2020-12-17 08:56:30 所属栏目:安全 来源:网络整理
导读:我想知道如何做的工作这个片段: //htmldiv ng-app="app"div ng-controller="AppCtrl" a my-dir ng-repeat="user in users"{{user.name}}/a/div/div//jsvar app = angular.module('app',[]); app.controller("AppCtrl",function ($scope) { $scope.users = [
我想知道如何做的工作这个片段:
//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 
                  }
                };
            });

我知道这是关于编译阶段
但我没有得到点,所以一个简短的解释是
非常感谢。
提前致谢。

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

类似答案:

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

这是一个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);
      };
    }
  };
});

更清洁的解决方案 – 不使用ng点击所有:

管道: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);
        });  
      };
    }
  };
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读