将数据从一个控制器传递到另一个 Angular [英] Passing data from one controller to other Angular
问题描述
我有一个控制器,它使用 $http 获取 XML 文件并将其解析为 json 对象.这是'MainCtrl'.现在我想在其他控制器中获取相同的 json 对象,而不再通过 $http,因为我已经加载了 XML.
I have a controller which is fetching an XML file using $http and parsing it into a json object. This is 'MainCtrl'. Now I want to get the same json object in other controllers without again going through an $http because I have already loaded the XML.
这是我的第一个控制器
angularXML.controller('MainCtrl', ['$scope', '$http','courseDefService', function($scope, $http, courseDefService) {
$http.get(base_url + 'assets/js/angularxml/courseDef.xml').then(function(response) {
var chapters = [];
var courseDef = x2js.xml_str2json(response.data);
console.log(courseDef);
}
这是我的第二个控制器
angularXML.controller('chapterCtrl', ['$scope', '$routeParams', function($scope, $routeParams) {
$scope.chapterNumber = $routeParams.id;
var chapter = $scope.chapterNumber - 1; /* index starts from zero */
}
我想我需要使用工厂.但我不知道该怎么做.我尝试了一种在工厂内获取 XML 的实现.但是当我调用工厂方法时,它正在执行另一个我通过控制台确认的 ajax 请求.
I think I need to use factory. But I am not sure how to do that. I tried one implementation where I was fetching the XML inside the factory. But when I was calling the factory method, it was doing another ajax request which I confirmed through console.
请帮忙.
推荐答案
在控制器内进行 XHR 调用并不是最佳实践.如果您有可用数据,请在工厂中将其分开并注意不要重复调用.您的服务应该完全控制何时访问服务器以获取数据.控制器应该只访问服务.
Its not a best practice to make the XHR call within the controller. Separate it out in a factory and take care not to repeate the call If you have data available. Your service should have a full control over when to hit the server to fetch data. Controllers should only access the service.
我可能会这样做:
App.factory('eywa', ['$http', function($http) {
var eywaFactory = {};
eywaFactory.data = '';
eywaFactory.load = function() {
this.data = $http.get('./assets/js/angularxml/courseDef.xml').then(function(data) {
return x2js.xml_str2json(data);
});
return this.data;
};
eywaFactory.get = function() {
return this.data === '' ? this.load() : this.data;
};
return eywaFactory;
}]);
并在控制器内部调用服务:
And call the service inside controller:
App.controller('MainCtrl', function($scope, eywa) {
eywa.get().then(function(data) {
$scope.courseDef = data;
});
});
这篇关于将数据从一个控制器传递到另一个 Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!