我有一个将元素推送到数组的指令,然后在视图上显示元素,问题是即使数组得到更新(日志显示正确的值),视图仍会显示空数组。我做错了什么?
注意:我不需要父母的$ scope范围,所有我添加/修改都在指令的范围内。
指令:
app.directive('streaming', function(){
return {
restrict: 'EA',
scope: {
live: '&',
data: '&',
},
controller: function($scope){
$scope.messages=[];
//.....
//Eventually this reaches $scope.messages.push({..});
},
templateUrl: '/directives/templates/streaming.html'
}});
模板:
<div class="row" >
<canvas id="canvas" width="640px" height="360px"></canvas>
</div>
<div ng-show="live" id="chat">
{{messages}}
<div ng-repeat="m in messages">
<div ng-if="m.type==0"><!--sistema-->
{{m.val}}
</div>
<div ng-if="m.type==1"><!--Usuario-->
{{m.val}}
</div>
</div>
</div>
答案 0 :(得分:1)
我必须将$scope.messages
修改包装在$scope.apply()
中,以使视图反映实际值。我不完全确定为什么。这解决了我的问题
答案 1 :(得分:0)
重写你的指令:
app.directive('streaming', function() {
var controller = ['$scope', function ($scope) {
function init() {
// Copy any stuff from the scope you need
$scope.messages = angular.copy($scope.messages);
};
init();
$scope.messages=[];
//.....
//Eventually this reaches $scope.messages.push({..});
}],
return {
restrict: 'EA',
scope: {
live: '&',
data: '&',
messages: '&',
},
controller: controller,
templateUrl: '/directives/templates/streaming.html'
}
});