use*_*320 9 json angularjs requirejs-text
我曾经使用RequireJS和Backbone,并使用requirejs/text和requirejs-plugins来加载我通常用于配置的本地json文件.
如何使用AngularJS实现相同的目标?
每个人似乎都建议使用$ http,但这是唯一的方法吗?如果我有20个配置文件,我真的需要拨打20个电话吗?
也许类似于ng-constant的东西是"首选"方式?
这就是我做的.但它使用$ http,所以我希望有人有更好的解决方案.
app.js:
var myModule = angular.module('myApp', []);
myModule.config(function($routeProvider, $locationProvider) {
$routeProvider.when('/', {
templateUrl: 'html/home.html',
controller: 'MainCtrl as ctrl',
resolve: {
initializeData: function($q, $timeout, myService) {
return myService.promiseToHaveData();
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
myService.js:
var myModule = angular.module('myApp');
myModule.service('myService', function($http, $q) {
var _this = this;
this.promiseToHaveData = function() {
var defer = $q.defer();
$http.get('someFile.json')
.success(function(data) {
angular.extend(_this, data);
defer.resolve();
})
.error(function() {
defer.reject('could not find someFile.json');
});
return defer.promise;
}
});
Run Code Online (Sandbox Code Playgroud)
然后我可以在任何地方注入myService,它将包含json文件中的所有字段.
我猜你也可以制作你的.json文件.js文件,让它们公开一个全局变量,并在你的index.html中引用它们
你能使用jQuery的getJSON函数吗?
例如:
$.getJSON("config-1.json", function( data ) {
// do whatever you want
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
61420 次 |
| 最近记录: |