从一个控制器将数据传递到其他角 [英] Passing data from one controller to other Angular

查看:131
本文介绍了从一个控制器将数据传递到其他角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器,该控制器使用获取$ HTTP和它解析成JSON对象的XML文件。这是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.

下面是我的第一个控制器

Here is my first controller

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

这是我的第二个控制器

And here is my second controller

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最佳实践。分离出来的一家工厂和照顾。如果您的可用数据不repeate呼叫。您的服务应该对当打服务器获取数据的完全控制。控制器应该只访问该服务。

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

和调用内部控制服务:

App.controller('MainCtrl', function($scope, eywa) { 
    eywa.get().then(function(data) {
      $scope.courseDef = data;
    });
});

这篇关于从一个控制器将数据传递到其他角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆