重置范围变量Angular.js

Reset a scope variable - Angular.js

本文关键字:Angular js 变量 范围      更新时间:2023-09-26

我想确保每次页面更改时,isSearchVisible作用域变量总是从false开始。我应该如何实施它?

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

在每个页面中,根作用域变量isSearchVisiblefalse,因为MainController

当您进入配置文件页面(ProfileController)时,本地作用域变量将变为true,这很好。

但是当您离开此页面时,根作用域变量也更改为true$rootScope变量和$scope变量之间没有分离。

每次页面更改时,我应该如何将isSearchVisible重置为false,除非控制器直接更改它?

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

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

您必须使用服务来共享数据:

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 = {};
        }
    };
});

从这里注入并请求每个控制器。