【问题标题】:ng-attr not evaluating on directive elementng-attr 不评估指令元素
【发布时间】:2014-04-13 13:33:18
【问题描述】:

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

<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 被分配了“{{question.id}}”而不是 question.id 的值。我尝试使用 ng-attr-cid="question.id" 但这也不起作用。最重要的是,ctype 被评估为未定义。

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

有人可以解释一下我缺少什么吗?

【问题讨论】:

    标签: angularjs coffeescript


    【解决方案1】:

    在隔离范围内(当您在指令上指定范围对象时会得到什么),您可以根据原始元素的属性将变量导入范围。

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

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

    总之

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

    这是plnkr showing the fix

    【讨论】:

      【解决方案2】:

      尚不完全清楚为什么您需要 cid 属性上的 ng-attr 前缀,但如果您确实需要这样做,那么不幸的是,您的“cid”隔离范围值会干扰 angular 如何处理的一些实现细节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.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-04
        • 1970-01-01
        相关资源
        最近更新 更多