2014-04-13 55 views
4

我試圖使用元素屬性將數據從控制器傳遞到隔離的作用域。下面是我的看法標籤: ng-attr不對指令元素進行評估

<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 =「」的元素。

能有人請解釋我缺少的是什麼?

回答

1

在一個孤立的範圍(當你指定一個指令一個範圍對象,你會得到什麼),你可以變量導入在原有基礎上元素的屬性範圍。

在這種情況下,就沒有必要使用ng-attr,因爲我們的指令將處理斂值。

  • "="適用於想要複製變量的情況,因此您只需提供變量名稱即可。 cid="question.id"
  • "@"是當你想將它傳遞給你的指令之前,插一個變量,例如cid="{{question.id}}"。傳遞原始字符串也非常方便。

總之

  • ng-attr
  • 改變指令scope.cid"@"OR使用cid="question.id"在你的HTML
  • 檢查questions(不知道價值,如果這是故意pluralised或者不是,因爲ctype在您的指令中未定義,這意味着questions也未定義。

這裏是一個plnkr showing the fix

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.