Matan Yadaev
Matan Yadaev

Reputation: 3338

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?

Upvotes: 0

Views: 2729

Answers (2)

Oam Psy
Oam Psy

Reputation: 8663

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.

Upvotes: 0

madu
madu

Reputation: 354

add an event listener to the root scope and then do what you want

$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 ... });

Upvotes: 0

Related Questions