AngularJS 从 URL 获取动态填充数据的服务函数

AngularJS service function to get data dynamically populated from URL

我正在尝试使用 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 我已经 url 创建了 /ajax_countries/ 其中 return JSON 格式化数据的方式与国家/地区列表相同

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

不工作。这是上面示例中的 codeopen link。

您可以考虑创建一个工厂国家、州和城市,这样它们的逻辑就会分开。

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

这样你就可以

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;
    });
}]);

如果您使用异步的 $http 那么 service.getCountry 是 return undefined 因为完成 asynchronous 事件需要一些时间并且 js 在该事件完成之前不会保持,而是执行其余代码。

在这里,当你使用 $scope.countries = CustomerService.getCountry(); 时你可能会得到未定义的原因是它的 return undefined 因为它直到 ajax 才完成然后 returnreturn data;

如果您不太熟悉,我们可以使用 angular promises1, angular 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
});

你做错了。您已经创建了一个局部变量 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;
}]);