将变量传递给 Angular 指令 [英] Passing variable to Angular Directive

查看:24
本文介绍了将变量传递给 Angular 指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个指令 myDir 并且我在 ng-repeat 中像这样调用它

If I have a directive myDir and I call it within ng-repeat like so

<my-dir myindex="{{$index}}"></my-dir>

我如何访问 myindex?当我在 postLink 函数中使用 attrs.myindex 时,我得到了实际的字符串 {{$index}}.当我检查 html 时,它实际上是 myindex="2".

How can I access myindex? I get actual string {{$index}} when I use attrs.myindex within postLink function. When I inspect html, it actually says myindex="2".

推荐答案

尝试

<my-dir myindex="$index"></my-dir>

然后

app.directive('myDir', function () {
  return {
    restrict: 'E',
    scope: {
      myindex: '='
    },
    template:'<div>{{myindex}}</div>',
    link: function(scope, element, attrs){
      scope.myindex = attrs.myindex;
      console.log('test', scope.myindex)
    }
  };
})

演示:Plunker

这篇关于将变量传递给 Angular 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆