Hen*_*Zhu 44 controller angularjs
我有一个Angular服务/提供程序,它为我的控制器提供json数据,效果很好:
angular.module('myApp.services', ['ngResource']).
factory("statesProvider", function($resource){
return $resource('../data/states.json', {}, {
query: {method: 'GET', params: {}, isArray: false}
});
});
Run Code Online (Sandbox Code Playgroud)
但我还需要将json数据从另一个文件提供给同一个控制器counties.json.
我在哪里可以找到如何编写一个服务器来为我的控制器提供这两个文件?
Dmi*_*eev 94
您可以更新服务以返回资源的哈希,而不是单个哈希:
angular.module('myApp.services', ['ngResource']).
factory("geoProvider", function($resource) {
return {
states: $resource('../data/states.json', {}, {
query: { method: 'GET', params: {}, isArray: false }
}),
countries: $resource('../data/countries.json', {}, {
query: { method: 'GET', params: {}, isArray: false }
})
};
});
Run Code Online (Sandbox Code Playgroud)
您将能够使用它.query()在最后添加您的函数名称geoProvider.states.query(),geoProvider.countries.query()并且myApp.services必须将其注入您的控制器,然后将geoProvider服务注入控制器本身.
我假设你想要在两个文件都加载时执行一些代码.承诺对此非常有效.我认为资源不会返回承诺,但您可以使用$ http服务进行简单的ajax调用.
在这里,我为两个数据文件定义了一个服务,第三个服务返回了在两个文件加载完成后得到满足的promise.
factory('states',function($http) {
return $http.get('../data/states.json');
}).
factory('countries',function($http) {
return $http.get('../data/countries.json');
}).
factory('statesAndCountries', function($q, states, countries) {
return $q.all([states, countries]);
});
Run Code Online (Sandbox Code Playgroud)
然后在你的控制器中:
statesAndCountries.then(function(data) {
var stateData = data[0];
var countryData = data[1];
// do stuff with stateData and countryData here
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31832 次 |
| 最近记录: |