当ajax调用更改其值时,不会更新AngularJS中的ng-repeat列表

时间:2014-04-09 18:50:22

标签: javascript ajax angularjs angularjs-scope angularjs-ng-repeat

我完全糊涂了。当ajax调用改变其值时,为什么我的ng-repeat刷新?我在这里见过很多Q& As,但他们都没有谈到ajax电话。

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);
    });
}

控制台确实记录了服务器返回的数组。但是html中的列表从未更新过。如果我使用$scope.$apply,则会发生与$digest相关的错误。

控制台输出

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

所以它是服务器返回的root的结构。这是数据类型的问题吗?因为它是Object而不是Array。我使用Golang作为服务器,并使用json.Marshal()打包来自MongoDB的数据。

更新

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

后者的输出为[]。这可能是因为$ http的异步,所以它的原因是什么?

最终

我知道为什么。我使用了一个名为jsTree的插件,它会对节点进行一些装饰,因此我插入的节点将被覆盖。

谢谢大家。

1 个答案:

答案 0 :(得分:0)

我已经测试了你的代码,并且正如tymeJV所说,你的实现没有问题,我建议检查控制台窗口是否存在一些可能的错误。

示例:

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);
    });
}   

实例:http://plnkr.co/edit/Grlgfob6tjE63JizWdCD?p=preview