AngularJS访问方法之外的$ scope

时间:2016-02-04 06:16:57

标签: javascript angularjs

这是我在控制器中的方法,我想访问下面给定方法之外的$ scope.oldcats。 在方法中使用console.info($scope.oldcats);输出数据, 但使用console.info($scope.oldcats);外部功能显示undefined

$scope.loadPost = function() { //Issues a GET request to /api/post/:id to get a Post to update
    $scope.posts = Post.get({ id:$stateParams.id}, function(response){
       $scope.posts = response.data;
       $scope.posts.selcats = response.data.categories;
       var cats = $scope.posts.categories;
       $.each(cats, function(arrayID,group) {
           $scope.allCats.push(group.id);
       });
       $scope.oldcats = $scope.allCats; // <- i want to access it
       console.info($scope.oldcats); // <- output displays data
   });
  };

  $scope.loadPost(); // Load a Post which can be edited on UI

  console.info($scope.oldcats); // <- output display undefined

2 个答案:

答案 0 :(得分:0)

在API调用完成之前调用函数外部的console.info。因此,它会记录undefined。但是在API调用完成后调用函数内部的控制台。 这称为异步行为。 看看Promises

这个thinkster教程将有助于更好地理解异步行为:Thinkster-understand promises

答案 1 :(得分:0)

你犯了几个错误,你应该使用承诺:

$scope.loadPost = function(){ //Issues a GET request to /api/post/:id to get a Post to update        
    $scope.posts = function(){
       var deferred = $q.defer();
       Post.get({ id:$stateParams.id}, function(response){
           $scope.posts = response.data;
           $scope.posts.selcats = response.data.categories;
           var cats = $scope.posts.categories;
           $.each(cats, function(arrayID,group) {
               $scope.allCats.push(group.id);
           });
           $scope.oldcats = $scope.allCats; // <- i want to access it
           deferred.resolve($scope.oldcats);
           console.info($scope.oldcats); // <- output displays data
    });
    return deferred.promise;
  };
  return $scope.posts;
};

$scope.loadPost()().then(function(res){
    console.info(res);
});