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

时间:2015-09-03 17:40:13

标签: javascript angularjs

我有一个角度JS应用程序,它有一个介绍页面和一个工作'页.. 我的html的简化版本如下:



    function startSearch(){
        var searchValue = $('#searchInput').val();

        $.post('./ifsearch-test.php',
            {searchterm: searchValue},
            function(data,status){
                showSearchResult(data);
        });

        $('#searchInput').val('');
    }

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




我遇到的问题是当我从一条路线移动到另一条路线时,即从#34; /"到" /#working" MyController被重新初始化,现在已经完成的http请求被丢弃了。如何跨两条路由共享同一个控制器实例?

2 个答案:

答案 0 :(得分:2)

绑定到控制器的每个视图都会创建它自己的控制器实例。 Controller只由视图继承共享,也就是说,子视图可以访问父控制器的同一个实例。

然而,这似乎不是你想要做的。听起来你想要做的就是在控制器实例之间保留一些数据(通过http请求获取)的状态。在这种情况下,您可能想要做的是将请求逻辑移动到服务(或工厂)中,然后将该服务注入控制器。由于服务是角度的单例,因此您的请求现在只能执行一次。

示例:

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

});

答案 1 :(得分:0)

您可以在定义路线时始终通过控制器

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

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