ng-repeat list in AngularJS isn't updated when

2019-02-17 21:08发布

问题:

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