简体   繁体   English

如何获取多个Angular JS路由来共享一个控制器实例?

[英]How can I get multiple Angular JS routes to share a single controller instance?

I have an angular JS app which has an intro page and a 'working' page.. A simplified version of my html looks like: 我有一个有角度的JS应用程序,它具有一个简介页面和一个“工作”页面。.我的html的简化版本如下:

 (function () { 'use strict'; var MyController = function (_, $rootScope, $scope, $location, $anchorScroll, $timeout, gettextCatalog, service) { var self = this; console.log("test"); //More code which invokes http requests }; angular.module('my.controller', [ 'gettext', 'lodash', 'ngRoute', 'ngSanitize', 'ngAnimate', 'my.service' ]).config( function ($routeProvider) { $routeProvider.when('/', { 'templateUrl': 'modules/home.html', 'reloadOnSearch': false }).when('/chatting', { 'templateUrl': 'modules/working.html', 'reloadOnSearch': false }); }).controller('MyController', MyController); }()); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> <html id="ng-app" ng-app="app" ng-controller="MyController as myCtrl"> <head> <link rel="stylesheet" href="styles/main.css"> <title>What's in Theaters</title> </head> <body id="app-body" class="dialog-body"> <div style="height: 100%; width: 100%" ng-view></div> <script src="bower_components/angular/angular.js"></script> <script src="bower_components/angular-gettext/dist/angular-gettext.js"></script> <script src="bower_components/angular-route/angular-route.js"></script> <script src="bower_components/angular-sanitize/angular-sanitize.js"></script> <script src="bower_components/angular-animate/angular-animate.js"></script> <script src="app.js"></script> <script src="modules/my-controller.js"></script> </body> </html> 

The problem I have is that when I move from one route to another ie from "/" to "/#working" the MyController is re-initialized and the http requests which were already completed are now discarded.. How do I share the same instance of the controller across both routes? 我遇到的问题是,当我从一条路径移动到另一条路径时,即从“ /”移动到“ /#working”时,MyController重新初始化,并且已经完成的http请求现在被丢弃。两条路线上的控制器实例?

Each view bound to a controller creates it's own instance of that controller. 绑定到控制器的每个视图都将创建其自己的控制器实例。 Controller's are only shared by view inheritance, that is, a child view will have access to the same instance of the parent's controller. 只能通过视图继承共享控制器的视图,也就是说,子视图将有权访问父控制器的相同实例。

However that doesn't seem to be what you are trying to do. 但是,这似乎并不是您要尝试执行的操作。 It sounds like what you want to do is persist the state of some data (acquired via http requests) between controller instances. 听起来您想要做的是在控制器实例之间保留某些数据状态(通过http请求获取)。 In that case, what you'd likely want to do is move the request logic into a service (or factory) and then inject that service into the controller. 在这种情况下,您可能要做的就是将请求逻辑移至服务(或工厂)中,然后将该服务注入控制器中。 Since services are singletons in angular, your requests should now only be performed once. 由于服务是成角度的单身人士,因此您的请求现在仅应执行一次。

Example: 例:

var MyController = function (_, $rootScope, $scope, $location, $anchorScroll, $timeout, gettextCatalog, service, yourHttpService) {
        var self = this;
        console.log("test");

// get data from your http service here... perhaps $scope.data = yourHttpService.getData(...).then(...);
    };


.factory('yourHttpService', function($http, $q) {

    var dataCache = ...; // create a local memory db to store the data

    return {
       getData: function(...) {
          var deferred = $q.defer();

          // check to see if the data is already cached, if so resolve the promise with the cached data

          // if data is not cached, perform the $http request to fetch the data, then cache it and resolve your promise

          return deferred.promise;
       };
    };

});

You can always pass your controller while defining your routes 您始终可以在定义路线时通过控制器

$routeProvider.when('/', {
                    'templateUrl': 'modules/home.html',
                    'controller' : MyController,
                    'reloadOnSearch': false

                }).when('/chatting', {
                    'templateUrl': 'modules/working.html',
                    'controller' : MyController,
                    'reloadOnSearch': false
                });

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

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