ng-attr不评估指令元素

时间:2014-04-13 00:33:38

标签: angularjs coffeescript

我正在尝试使用元素属性将数据从控制器传递到隔离范围。这是我在视图中的标记:

<comment ng-attr-cid="{{question.id}}" ctype="questions"></div>

这是指令:

'use strict'

angular.module('arlo.directives').directive "comment", ['Comment', (Comment) ->
  directive =
    templateUrl: "angular/partials/comment.html"
    restrict: "E"
    scope:
      cid: "="
      ctype: "="

    link: (scope, element, attrs) ->
      scope.toggled = false
      scope.comment = null
      scope.comments

      scope.toggle = ->
        if scope.toggled is true then scope.toggled = false else scope.toggled = true
        scope.comment = null

      scope.addComment = ->
        Comment.addComment(scope.ctype, scope.cid, scope.comment).then ->
          scope.comments = Comments.commentsList
          scope.toggled = false
          scope.comment = null

      scope.loadComments = ->
        Comment.loadComments(scope.ctype, scope.cid).then ->
          scope.comments = Comments.commentsList

      scope.loadComments()
]

问题是cid已被分配&#34; {{question.id}}&#34;而不是question.id的值的值。我试图使用ng-attr-cid =&#34; question.id&#34;但这也不起作用。最重要的是,ctype正在评估为未定义。

如果我在任何其他元素上添加ng-attr-cid,它会评估并添加cid =&#34;&#34;到元素。

有人可以解释一下我缺少的东西吗?

2 个答案:

答案 0 :(得分:1)

在隔离范围(在指令上指定范围对象时获得的范围)中,可以根据原始元素的属性将变量导入范围。

在这种情况下,不需要使用ng-attr,因为我们的指令将处理抓取值。

  • "="用于复制变量,因此您只需提供变量名称,例如cid="question.id"
  • "@"用于在将变量传递给指令之前插入变量,例如cid="{{question.id}}"。传递原始字符串也非常方便。

简而言之

  • 放弃ng-attr
  • 将指令scope.cid更改为"@" 使用HTML中的cid="question.id"
  • 检查questions的值(不确定这是否故意复数,因为ctype未在您的指令中定义,这意味着questions也未定义。

这是plnkr showing the fix

答案 1 :(得分:0)

为什么你需要在cid属性上使用ng-attr前缀并不完全清楚,但如果你确实需要这样做,那么很遗憾你的'cid'隔离范围值会干扰角度处理方式的一些实现细节NG-ATTR - *

您可以通过在指令中使用链接函数来笨拙地解决这个问题,该函数遵循将由ng-attr-cid创建的'cid'属性,并删除隔离范围定义中的现有cid: '='属性

... your existing directive definition ...
link: function link(scope, elem, attrs) {
  attrs.$observe('cid', function(val) {
    scope['cid'] = val;
  });
}
... etc, etc ...

这会在cid属性上设置一个观察者,并在每次更改时更新范围。

See plnkr.