AngularJS服务函数,用于从URL动态填充数据

时间:2015-12-03 12:09:21

标签: javascript angularjs angularjs-directive angularjs-scope angular-services

我正在尝试使用this example实现动态表单。

myApp.factory("CustomerService", ['$filter', function($filter){
 var service = {};
  var countrylist = [
        { "id": 1, "country": "USA" },
        { "id": 2, "country": "Canada" },
        { "id": 3, "country": "India" },
  ];
var statelist = [
    {"Id":1, "state":"Alaska", "countryId": 1},
    {"Id":2, "state":"California", "countryId": 1},
    ...
 ];
var citylist = [
    {"Id":1, "city":"Anchorage", "stateId": 1},
    ...
  ];
service.getCountry = function(){    
    return countrylist;
  };

service.getCountryState = function(countryId){
    var states = ($filter('filter')(statelist, {countryId: countryId}));
    return states;
  };


service.getStateCity = function(stateId){    

 var items = ($filter('filter')(citylist, {stateId: stateId}));      
  return items;
 };

 return service;

 }]);

我想要的是从json http响应填充statelistcountrylist我创建了网址/ajax_countries/,它以与countrylist相同的方式返回JSON格式的数据

   service.getCountry = function(){    
       return $http.get('/ajax_countries/').success(function(data) {
           return data;
       })
      }

不工作。以下是上述示例中的codeopen链接。

3 个答案:

答案 0 :(得分:1)

你做错了。您已创建用于存储函数的局部变量service。相反,您应该将其存储在全局范围内。

<强> See Codepen Here

myApp.factory("CustomerService", ['$filter', function($filter) {

  this.countrylist = [
            { "id": 1, "country": "USA" },
            { "id": 2, "country": "Canada" },
            { "id": 3, "country": "India" },
    ];

  this.statelist = [
    {"Id":1, "state":"Alaska", "countryId": 1},
    {"Id":2, "state":"California", "countryId": 1},
    {"Id":3, "state":"New York", "countryId": 1},
    {"Id":4, "state":"New Brunswick", "countryId": 2},
    {"Id":5, "state":"Manitoba", "countryId": 2},
    {"Id":6, "state":"Delhi", "countryId": 3},
    {"Id":7, "state":"Bombay", "countryId": 3},
    {"Id":8, "state":"Calcutta", "countryId": 3}
  ];

  this.citylist = [
    {"Id":1, "city":"Anchorage", "stateId": 1},
    {"Id":2, "city":"Fairbanks", "stateId": 1},
    {"Id":3, "city":"Lakes", "stateId": 1},
    {"Id":4, "city":"Palmer", "stateId": 1},
    {"Id":5, "city":"Adelanto", "stateId": 2},
    {"Id":6, "city":"Artesia", "stateId": 2},
    {"Id":7, "city":"Benicia", "stateId": 2},
    {"Id":8, "city":"Clovis", "stateId": 2},
    {"Id":9, "city":"Dublin", "stateId": 2},
    {"Id":10, "city":"Manhattan", "stateId": 3},
    {"Id":11, "city":"Bronx", "stateId": 3},
    {"Id":12, "city":"Brooklyn", "stateId": 3},
    {"Id":13, "city":"Queens", "stateId": 3},
    {"Id":14, "city":"Staten Island", "stateId": 3},
    {"Id":15, "city":"Bathurst", "stateId": 4},
    {"Id":16, "city":"Campbellton", "stateId": 4},
    {"Id":17, "city":"Dieppe", "stateId": 4},
    {"Id":18, "city":"Edmundston", "stateId": 4},
    {"Id":19, "city":"Fredericton", "stateId": 4},
    {"Id":20, "city":"Miramichi", "stateId": 4},
    {"Id":21, "city":"Moncton", "stateId": 4},
    {"Id":22, "city":"Brandon", "stateId": 5},
    {"Id":23, "city":"Dauphin", "stateId": 5},
    {"Id":24, "city":"Flin Flon", "stateId": 5},
    {"Id":25, "city":"Morden", "stateId": 5},
    {"Id":26, "city":"Portage la Prairie", "stateId": 5},
    {"Id":27, "city":"Selkirk", "stateId": 5},
    {"Id":28, "city":"Steinbach", "stateId": 5},
    {"Id":29, "city":"Thompson", "stateId": 5},
    {"Id":30, "city":"Winkler", "stateId": 5},
    {"Id":31, "city":"South Delhi", "stateId": 6},
    {"Id":32, "city":"North Delhi", "stateId": 6},
    {"Id":33, "city":"East Delhi", "stateId": 6},
    {"Id":34, "city":"West Delhi", "stateId": 6},
    {"Id":35, "city":"Old Delhi", "stateId": 6},
    {"Id":36, "city":"New Delhi", "stateId": 6},
    {"Id":37, "city":"Yamuna Paar", "stateId": 6},
    {"Id":38, "city":"Chembur", "stateId": 7},
    {"Id":39, "city":"Borivali West", "stateId": 7},
    {"Id":40, "city":"Ghatkopar West", "stateId": 7},
    {"Id":41, "city":"Juhu", "stateId": 7},
    {"Id":42, "city":"Mira Road", "stateId": 7},
    {"Id":43, "city":"Powai", "stateId": 7},
    {"Id":44, "city":"Virar West", "stateId": 7},
    {"Id":45, "city":"Rajarhat", "stateId": 8},
    {"Id":46, "city":"Park Street", "stateId": 8},
    {"Id":47, "city":"Golpark", "stateId": 8},
    {"Id":48, "city":"Chandan Nagar", "stateId": 8}
];

  this.getCountry = function() {
    return this.countrylist;
  };

  this.getCountryState = function(countryId) {
    var states = ($filter('filter')(this.statelist, {
      countryId: countryId
    }));
    return states;
  };

  this.getStateCity = function(stateId) {
    var items = ($filter('filter')(this.citylist, {
      stateId: stateId
    }));
    return items;
  };

  return this;
}]);

答案 1 :(得分:0)

您可以考虑创建工厂国家/地区,州和城市,以便将每个逻辑分开。

注意:这只是一个必须修改和实现真实的草图。

这样你会有

angular.module('Services')
.factory('countryService', [
    '$http', function ($http) {
        var settings = {
            apiUrl: '/ajax_countries/',
        };
        return {
            getCountry: function(callback){    
                $http.get(settings.apiUrl).success(callback);
            }
        };
    }
]);

(...)

angular.module('Services')
.factory('stateService', [
    '$http', function ($http) {
        var settings = {
            apiUrl: '/ajax_states/',
        };
        return {
            getCountryState: function(countryId, callback){    
                $http.get(settings.apiUrl, {countryId: countryId}).success(callback);
            }
        };
    }
]);

(...)

angular.module('Services')
.factory('cityService', [
    '$http', function ($http) {
        var settings = {
            apiUrl: '/ajax_cities/',
        };
        return {
            getStateCity : function(stateId, callback){    
                $http.get(settings.apiUrl, {stateId: stateId}).success(callback);
            }
        };
    }
]);

现在,例如在您的控制器上,您可以注入服务。

angular.module('myApp', ['Services'])
.controller('mainCtrl',['countryService','stateService','cityService',
function(countryService,stateService,cityService){

    countryService.getCountry(function(data){
        $scope.countryList = data;
    });

    stateService.getCountryState(countryId, function(data){
        $scope.states  = data;
    });

    cityService.getStateCity(stateId, function(data){
        $scope.items = data;
    });
}]);

答案 2 :(得分:0)

如果您使用$http是异步的,那么service.getCountry将返回undefined,因为要完成asynchronous事件需要一些时间并且js不能保留到要完成该事件,它将执行其余代码。

在这里,你可能会在使用$scope.countries = CustomerService.getCountry();原因后返回未定义的原因是它返回undefined因为它在ajax完成后才会保留,然后返回return data; < / p>

所以我们可以做的是使用angular promises1angular promises2搜索,如果您不太熟悉它。

做到这一点

 service.getCountry = function(){    
   return $http.get('/ajax_countries/'); //this will return a js promise
 }

当你调用函数时,执行如下操作,

CustomerService.getCountry().then(function(data) {
    //success
   $scope.countries = data;
}, function() {
    // error
});