2016-07-28 45 views
0

我有內部控制器的以下功能:納克重複 - 當陣列在控制器改變不更新視圖,使用控制器作爲語法

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

如何更新這些數據?它是否與第三方像jQuery? – AranS

+0

它正在通過一些其他操作更新,未在此處顯示以保持問題清晰。 –

+0

[[d.name]]替換爲大括號 – gyc

回答

0

您正在更改數組的參考。這就是爲什麼數據沒有在UI中得到更新的原因。您可以更新數據如下:

function getData(){ 
    myServe.getData().then(function(data){ 
     ctrlScope.myData.length = 0; 
     ctrlScope.myData.push.apply(ctrlScope.myData, data); 
    }); 
} 
+0

是的,我已經嘗試過,但沒有運氣。 –

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(); 
     }; 
+0

我忘了在代碼中添加$ scope。$ evalAsync,它基本上排隊了當前摘要循環中的更新。 $ scope。$ apply不是必需的,因爲我們不會超出角度範圍。當我們在角度範圍之外進行更新時,這是非常必要的,這不是這裏的場景。 –

相關問題