AngularJs location path change without all controllers resetting

后端 未结 2 1482
醉酒成梦
醉酒成梦 2021-02-06 06:23

Short version of my question is: How do I change the URL without need to trigger route change or without need to run all the controllers on the currently displayed page?

2条回答
  •  渐次进展
    2021-02-06 07:29

    You can use $locationChangeStart event to store the previous value in $rootScope or in a service. When you come back, just initialize all the previously stored values from the $rootScope. Check this quick demo using $rootScope.

    var app = angular.module("myApp", ["ngRoute"]);
    app.controller("tab1Ctrl", function($scope, $rootScope) {
        if ($rootScope.savedScopes) {
            for (key in $rootScope.savedScopes) {
                $scope[key] = $rootScope.savedScopes[key];
            }
        }
        $scope.$on('$locationChangeStart', function(event, next, current) {
            $rootScope.savedScopes = {
                name: $scope.name,
                age: $scope.age
            };
        });
    });
    app.controller("tab2Ctrl", function($scope) {
        $scope.language = "English";
    });
    app.config(function($routeProvider) {
        $routeProvider
            .when("/", {
                template: "

    Tab1 content

    Name:

    Age:

    Fill the details and click on Tab2

    ", controller: "tab1Ctrl" }) .when("/tab2", { template: "

    Tab2 content

    My language: {{language}}

    Now go back to Tab1

    ", controller: "tab2Ctrl" }); });
    
    
    
    
    
        Tab1
        Tab2
        

提交回复
热议问题