【问题标题】:ng-Repeat returning undefined within $scope.$watchCollectionng-Repeat 在 $scope.$watchCollection 内返回 undefined
【发布时间】:2015-06-23 16:29:03
【问题描述】:

当我在第 5 行 console.log(result) 时,它返回就好了。第 11 行的 console.log($scope.notes) 返回 undefined。有什么想法吗?

这是我的控制器:

$scope.$watchCollection = (['parent_id', 'parent_type'], function(){
    $scope.loadNotes = function(){
        $http.get('/api/notes/' + $scope.parent_id + "/" + $scope.parent_type).success(function(result){
            console.log(result);
            $scope.notes = result;
            return result;
        });
    }
    $scope.notes = $scope.loadNotes();
    console.log($scope.notes);
});

【问题讨论】:

  • Schw2iizer,我已经发布了答案,是否消除了您的疑问并给出了答案?
  • 好的,非常感谢。

标签: angularjs ng-repeat ng-init


【解决方案1】:

因为$http.get 是异步的,所以第 11 行在第 5 行之前执行,所以你在那里没有定义。

异步是指执行不等待 $http 返回承诺,它只是继续执行到下一行。

【讨论】:

    【解决方案2】:

    这是一种返回 Promise 的方法,因此代码将等待异步调用完成,然后再继续定义$scope.notes

    $scope.$watchCollection = (['parent_id', 'parent_type'], function(){
        $scope.loadNotes = function(){
            return $http.get('/api/notes/' + $scope.parent_id + "/" + $scope.parent_type).success(function(result){
                console.log(result);
                //$scope.notes = result;
                return result;
            });
        }
        $scope.loadNotes().then(function(loadedNotes){
            $scope.notes = loadedNotes;
            console.log($scope.notes);
        });
    
    });
    

    【讨论】:

    • 这也很棒。感谢您的回答。
    猜你喜欢
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多