在ajax调用中设置控制器属性

时间:2015-03-16 20:51:07

标签: javascript angularjs

我是AngularJS的新手,我对控制器属性有疑问。我创建了一个名为anuncio的属性,该属性有一个对象数组,如下图所示:

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

anuncioModule.controller('RegistrationController',['$http',function ($http){


    this.anuncios;


    this.loadAnuncios = function loadAnuncios(){

         $http.get('http://localhost:8080/pederofer/anuncios/get.action').then(function(result){

             this.anuncios.push.apply(this.anuncios, result.data);
        });

    }


}]);

当我使用函数loadAnuncios调用我的webservice并尝试使用“this.anuncios”直接设置值时,我收到消息“this.anuncios is undefined”。但是如果我创建一个名为anuncs的var并设置“this.anuncios = anucs”,而不是将我的AJAX调用直接设置到this.anuncios中,我将其设置为anucs,如图所示,它可以工作。

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

var anuncs =[]; 

anuncioModule.controller('RegistrationController',['$http',function ($http){


    this.anuncios = anuncs ;


    this.loadAnuncios = function loadAnuncios(){

         $http.get('http://localhost:8080/pederofer/anuncios/get.action').then(function(result){

             anuncs.push.apply(anuncs, result.data);
        });

    }


}

我的问题是,为什么会有效?

1 个答案:

答案 0 :(得分:0)

我可能会建议以不同的方式处理你正在做的事情。

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

anuncioModule.controller('RegistrationController', ['$scope', '$http', function ($scope, $http) {
    $scope.anuncios = [];
    $scope.loadAnuncios = function() {
        $http.get('http://localhost:8080/pederofer/anuncios/get.action').then(function(result) {
             $scope.anuncios = result.data;
        });
    };
}

我不知道这是不是你所追求的,但也许这会让你的灯泡消失。