ng-repeat list in AngularJS isn't updated when an ajax call changing its value

妖精的绣舞 提交于 2019-12-01 03:26:21

问题


I'm totally confused. Why doesn't my ng-repeat refresh when there's an ajax call changing its value? I've seen many Q&As here, but none of them talked about ajax call.

HTML:

<div class="row" ng-controller="EntryCtrl">
    <div id="treeview" class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
        <ul>
            <li ng-repeat="root in rootEntry">{{root.Name}}</li>
        </ul>
    </div>
</div>

JS:

function EntryCtrl ($scope, $http) {
    $scope.rootEntry = [];
    $http.get('read/root').success(function(root) {
        $scope.rootEntry = root;
        console.log($scope.rootEntry);
    });
}

And the console did log an array the server returned. But the list in html never got updated. If I used $scope.$apply, an error concerning $digest would happen.

Console Output

[Object]
    0: Object
        Attributes: null
        Id: "534580464aac494e24000001"
        Name: "Registry"
        Path: ""
        __proto__: Object
        length: 1
    __proto__: Array[0]

So it's the structure of root the server returns. Would it be the problem of data type? Because it's Object rather than Array. I use Golang as server and use json.Marshal() to pack the data from MongoDB.

Update

function EntryCtrl ($scope, $http) {
    $scope.rootEntry = [];
    $http.get('read/root').success(function(root) {
        $scope.rootEntry = root;
        console.log($scope.rootEntry);
    });
    console.log($scope.rootEntry);
}

The latter output is []. It's likely because of async of $http, so will it the reason?

Final

I know why. I used a plugin called jsTree, which will do some decorations with the node, so the node I inserted would be overwritten.

Thank you all.


回答1:


I've tested your code and as tymeJV said ,there is no problem with your implementation, i would suggest checking the console window for some possible errors.

Example:

function EntryCtrl ($scope, $http) {
    $scope.rootEntry = [];
    $http.get('https://api.github.com/users/mralexgray/repos').success(function(root) {
        $scope.rootEntry = root;
        console.log($scope.rootEntry);
    });
}   

Live example : http://plnkr.co/edit/Grlgfob6tjE63JizWdCD?p=preview



来源:https://stackoverflow.com/questions/22971468/ng-repeat-list-in-angularjs-isnt-updated-when-an-ajax-call-changing-its-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!