[英]Require a json file within angularjs using nodejs
I am using NodeJS and AngularJS. 我正在使用NodeJS和AngularJS。
Within Angular I would like to reference a json file and seperate parts of the json into different controllers. 在Angular中,我想引用一个json文件,并将json的不同部分放入不同的控制器中。
At the moment I am using http.get within the controller (see below). 目前,我正在控制器内使用http.get(请参见下文)。
var app = angular.module('app', []);
app.controller('introCtrl', function ($scope, $http) {
$http.get('src/data_json.js').success(function(data) {
$scope.intro = data;
});
This returns the entire json object within my first controller. 这将在我的第一个控制器中返回整个json对象。 However I would like to require the json file, store it as a variable, and have multiple controllers reference different parts.
但是我想要json文件,将其存储为变量,并让多个控制器引用不同的部分。
Is there a way to use nodejs to pass the json file to the angular controller Or is there a better way to require the json file using angular? 有没有一种方法可以使用nodejs将json文件传递给angular控制器,或者有更好的方法要求使用angular的json文件?
Many thanks 非常感谢
A good strategy would be store the http request in a service Service . 一个好的策略是将http请求存储在service Service中 。 Then you can made that service avaible to all your controllers by simply inject it.
然后,您只需注入一下即可使该服务可用于所有控制器。
If your using a REST
service you should also consider to use $resource . 如果您使用的是
REST
服务,则还应考虑使用$ resource 。
Thanks - I used a factory service in the end like you suggested... 谢谢-我最终按照您的建议使用了工厂服务...
var App = angular.module('App', []);
// Setting up a service to house our json file so that it can be called by the controllers
App.factory('service', function($http) {
var promise;
var jsondata = {
get: function() {
if ( !promise ) {
var promise = $http.get('src/data_json.js').success(function(response) {
return response.data;
});
return promise;
}
}
};
return jsondata;
});
App.controller('introCtrl', function (service , $scope) {
service.get().then(function(d) {
$scope.header = d.data.PACKAGE.ITEM[0]
})
});
App.controller('secondCtrl', function (service , $scope) {
service.get().then(function(d) {
$scope.title = d.data.PACKAGE.ITEM[1]
})
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.