简体   繁体   中英

Reset a scope variable - Angular.js

I want to make sure that isSearchVisible scope variable will always start on false on every page change. How should I implement it?

app.controller('MainController', function($rootScope) {
  $rootScope.isSearchVisible = false;
});
    
app.controller('ProfileController', function($scope) {
  $scope.isSearchVisible = true;
});
    
app.controller('AboutUsController', function($scope) {

});

In every page, the root scope variable isSearchVisible is false because of MainController .

When you enter the profile page ( ProfileController ), the local scope variable is turned to true , which is good.

But when you leave this page, the root scope variable changed as well to true . There is no separation between $rootScope variables and $scope variables.

How should I reset isSearchVisible to false on every page change, unless the controller directly changed it?

将事件侦听器添加到根范围,然后执行您想要的操作

$rootScope.$on('$routeChangeStart', function(next, current) { ... check your url if you want to show the search box in that url make $rootScope.showSearchBlock = true else make it false. and remove other instances of the $rootScope.showSearchBlock put this on your main controller ... });

You have to use services to share data:

app.factory('shareDataService', function () {   

 var formData = {};

    return {
        getData: function () {
            //You could also return specific attribute of the form data instead
            //of the entire data
            return formData;
        },
        setData: function (newFormData) {
            //You could also set specific attribute of the form data instead
            formData = newFormData
        },
        resetData: function () {
            //To be called when the data stored needs to be discarded
            formData = {};
        }
    };
});

Inject and request from each controller from here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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