Angularjs 控制器更改时,视图(模板)不更新
我有一个指令将元素推送到一个数组,然后在视图上显示元素,问题是,即使数组得到更新(日志显示正确的值),视图仍然显示空数组。我做错了什么 注意:我什么都不需要父级的$scope,我添加/修改的都是指令的作用域 指令:Angularjs 控制器更改时,视图(模板)不更新,angularjs,templates,updates,directive,Angularjs,Templates,Updates,Directive,我有一个指令将元素推送到一个数组,然后在视图上显示元素,问题是,即使数组得到更新(日志显示正确的值),视图仍然显示空数组。我做错了什么 注意:我什么都不需要父级的$scope,我添加/修改的都是指令的作用域 指令: app.directive('streaming', function(){ return { restrict: 'EA', scope: { live: '&', data: '&
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>
{{messages}}
{{m.val}}
{{m.val}}
像这样重写您的指令:
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'
}
});
我必须将
$scope.messages
修改包装在$scope.apply()
中,以获得反映实际值的视图。我不完全清楚为什么。这就解决了我的问题我们可以看到指令是如何在主HTML文档上调用的吗?只是它比这更重要。您可能会被孤立的作用域或某些角度指令的误用所阻止。如何将消息添加到数组中?我什么都不需要父范围,我希望使用我自己的范围和变量,然后这些变量将反映在指令视图上,而不是父视图上