2016-01-13 49 views
2

我試圖使用ng-repeat和指令顯示數組的元素。指令部分對解決方案很重要。但是數組的元素沒有被綁定並顯示一個空值。Angularjs在指令中綁定數組元素ng-repeat

的小提琴可以在http://jsfiddle.net/qrdk9sp5/

HTML

<div ng-app="app" ng-controller="testCtrl"> 
    {{chat.words}} 
    <test ng-repeat="word in chat.words"></test>  
</div> 

找到JS

var app = angular.module('app', []); 
app.controller("testCtrl", function($scope) { 
    $scope.chat = { 
     words: [ 
      'Anencephalous', 'Borborygm', 'Collywobbles' 
     ] 
    }; 
}); 
app.directive('test', function() { 
    return { 
     restrict: 'EA', 
     scope: { 
      word: '=' 
     }, 
     template: "<li>{{word}}</li>", 
     replace: true, 
     link: function(scope, elm, attrs) {} 
    } 
}); 

OUTPUT

["Anencephalous","Borborygm","Collywobbles"] 
• 
• 
• 

預期輸出

["Anencephalous","Borborygm","Collywobbles"] 
•Anencephalous 
•Borborygm 
•Collywobbles 

感謝您的幫助

回答

5

你沒有綁定word

您已使用隔離範圍。如果你不綁定它的scope屬性,它將無法工作。

scope: { 
    word: '=' 
}, 

嘗試這樣

<test word="word" ng-repeat="word in chat.words"></test> 

DEMO

+0

非常感謝很多 – Andy

+0

歡迎您:) @Andy –

0
var app = angular.module('dr', []); 
app.controller("testCtrl", function($scope) { 
    $scope.chat= {words: [ 
     'Anencephalous', 'Borborygm', 'Collywobbles' 
    ]}; 
}); 
app.directive('test', function() { 
    return { 
     restrict: 'EA', 
     scope: { 
      word: '=' 
     }, 
     priority: 1001, 
     template: "<li>{{word}}</li>", 
     replace: true,   
     link: function(scope, elm, attrs) {    
     } 
    } 
}); 

你的指令需要通過使用更高的優先級NG-重複之前運行,所以,當NG-重複克隆它能夠選擇你的修改的元素。

來自Directives user guide的「編譯/鏈接分離背後的原因」部分對how ng-repeat works有解釋。

當前的ng-repeat優先級是1000,所以比這個更高的值應該這樣做。

+0

請問您可以給代碼添加一些解釋嗎?爲什麼這會解決這個問題? – MeanGreen

相關問題