我在控制器中有以下功能:
app.controller("myCtrl", function(myServ, $scope){
var ctrlScope = this;
ctrlScope.myData = [];
function getData(){
myServ.getData().then(function(data){
$scope.$evalAsync(function(){
ctrlScope.myData = data;
});
});
}
getData(); // myData is initialised properly
ctrlScope.update = function(){
// Data has already changed in backend
getData(); //myData inside controller is updated but ng-repeat is not able to show on the view the updated array
};
});
HTML:
<div data-ng-controller="myCtrl as mc">
<span data-ng-repeat="d in mc.myData">{{d.name}}</span>
<button data-ng-click="mc.update()"> Update </button>
</div>
getData()
正确初始化ng-repeat
,但即使控制器更新了数据,也无法更新视图。
答案 0 :(得分:0)
您正在更改数组的引用。这就是为什么数据没有在UI中更新的原因。您可以按如下方式更新数据:
function getData(){
myServe.getData().then(function(data){
ctrlScope.myData.length = 0;
ctrlScope.myData.push.apply(ctrlScope.myData, data);
});
}
答案 1 :(得分:0)
添加
$scope().apply()
ctrlScope.update = function(){
// Data has already changed in backend
getData(); //myData inside controller is updated but ng-repeat is not able to show on the view the updated array
$scope().apply();
};