【问题标题】:AngularJS using ng-repeat on a $scope arrayAngularJS 在 $scope 数组上使用 ng-repeat
【发布时间】:2015-01-18 23:43:15
【问题描述】:

我有一个控制器,它通过 Parse 成功检索对象并将其推送到数组中:

var mySite = angular.module('mySite', []);

mySite.controller('listConnectors', ['$scope',
    function ($scope) {
        //Parse.initialize here;
        $scope.array = [];
        var TestObject = Parse.Object.extend("TestObject");
        var query = new Parse.Query(TestObject);
        query.find({
            success: function (results) {
                alert("Successfully retrieved " + results.length + " rows.");
                // Do something with the returned Parse.Object values
                for (var i = 0; i < results.length; i++) {
                    var object = results[i];
                    alert(object.id + ' - ' + object.get('foo') + " " + object.get('num'));

                    /***** Pushing onto array here *******/
                    $scope.array.push(object);

                }

                console.log($scope.array[0].attributes.foo); //Grabbed what was needed

            },
            error: function (error) {
                alert("Error: " + error.code + " " + error.message);
            }
        });
}]);

然后,我尝试循环并列出数组中每个对象的“foo”值,但没有成功,如上面的 console.log 所示。但是,什么都没有输出。好像可能没有执行或输入 ng-repeat:

    <li ng-repeat="eachElement in array">
    <a > {{eachElement.attributes.foo}}</a>
    </li>

任何帮助将不胜感激。谢谢!

【问题讨论】:

标签: javascript arrays angularjs angularjs-ng-repeat


【解决方案1】:

我能够修复它。感谢 Jonathan Lonowski 的评论和链接。

我不得不用 $apply 将 push 包装到数组中:

$scope.$apply(function(){
  $scope.array.push(object);
});

【讨论】:

    【解决方案2】:

    警报语句中的代码和 ng-repeat 指令中的代码不匹配。您的警报访问“x.id”,而您的 dom 绑定访问“x.attributes.id”。

    如果您的警报显示预期结果,则应按如下方式更改 HTML:

    <li ng-repeat="eachElement in array">
    <a > {{eachElement.id}}</a>
    </li>
    

    【讨论】:

    • 我的 'console.log($scope.array[0].attributes.foo); //Grabbed what was needed' 是我想要显示的,我应该删除警报,因为它使用 Parse 方法。请不要注意它。但无论哪种方式,{{eachElement.id}} 也不会输出任何内容。
    • 我本来打算放 eachElement.attributes.foo,但这也不起作用。很抱歉造成混乱。
    • 你试过 {{eachElement.attributes.foo}} 看看是否有效吗?我知道这不是您要找的房产。编辑:打败我。
    • 是的,也没有输出任何内容:(.
    猜你喜欢
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    相关资源
    最近更新 更多