简体   繁体   English

如何合并我的控制器AngularJS?

[英]How can I combine my controllers AngularJS?

I have my MainCtrl(called from $routeProvider and also from html): 我有我的MainCtrl(从$ routeProvider和html调用):

function MainCtrl($scope, $routeParams){
  //send data(see below) to AngularTemplate for apdate page
}

and I have my function, which fetch any data: 我有我的函数,该函数可获取任何数据:

function getData($scope, $http){
  /*
  * Nav Data(here my navigate-structure fo site)
  */
  $http({method: 'GET', url: 'data/main.json'}).
  success(function(data){
    //work with data and send it to MainCtrl
  });
  /*
  * News Data(Here my news)
  */
  $http({method: 'GET', url: 'data/news.json'}).
  success(function(data){
    //work with data and send it to MainCtrl
  });
}

Now I understand how can I send my data from one Ctrl to other using .$on and .$broadcast. 现在,我了解了如何使用。$ on和。$ broadcast将数据从一个Ctrl发送到另一个Ctrl。 But getData is not Angular Controller(it is a js-function) and it doesn't understend my args($scope and $http). 但是getData不是Angular Controller(它是一个js函数),并且不会低估我的args($ scope和$ http)。 Tell me plese, how I can call getdata the first page load and send data to MainCtrl. 告诉我,请问如何在第一次加载页面时调用getdata并将数据发送到MainCtrl。 And also if you know, tell me please what can I do with my MainCtrl, that he call only from $routeProvider. 另外,如果您知道的话,请告诉我MainCtrl我该怎么做,他只能从$ routeProvider呼叫。 Now at first it called from html(ng-controller), and after from $routeProvider. 现在首先从html(ng-controller)调用,然后从$ routeProvider调用。

put the getData function inside angular controller. 将getData函数放入角度控制器中。 and it will understand the $scope and $http services 它将了解$ scope和$ http服务

or make a protoype method set() of mainCtrl.... and pass $scope.var = value in it 或制作mainCtrl ....的原型方法set()并在其中传递$ scope.var = value

       MainCtrl.prototype = {
        set = function(value){
            $scope=value;

         }

    }

Wrap your data fetching code in a service. 将数据获取代码包装在服务中。 Here are two good SO answers that show how to do this: 以下是两个很好的SO答案,它们显示了如何执行此操作:

The examples above also show how to inject the service you create (eg, myService ) into a controller. 上面的示例还显示了如何将您创建的服务(例如, myService )注入到控制器中。 You can inject this service into as many controllers as necessary. 您可以根据需要将此服务注入到尽可能多的控制器中。 Since Angular services are singletons, there will only be one instance of your data fetching code, no matter how many controllers are injected with your service. 由于Angular服务是单例服务,因此无论您的服务中注入了多少个控制器,您的数据获取代码都将只有一个实例。

Your service can also cache the results of the $http request . 您的服务还可以缓存$ http请求的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM