如何在Angularjs中重置范围变量

时间:2014-11-03 11:12:52

标签: javascript jquery angularjs controller scope

您好我想知道重置angularjs中的scoep,这里是示例:

HTML:

<div ng-show="showSearchBlock">Search Block</div>

使用Javascript:

app.controller('MainController', function($rootScope) {
   $rootScope.showSearchBlock = false;
});

app.controller('ProfileController', function($scope) {
   $scope.showSearchBlock = true;
});

app.controller('AboutUsController', function($scope) {

});

如果我转到About us页面,$scpoe.showSearchBlock将为false(来自MainController)。

但是如果我路由到Profile页面$scope.showSearchBlock将是真的,然后我路由到About Us它仍然是真的。我希望$scope.showSearchBlock仅在ProfileController中出现,我该怎么做?

而且我不想在每个控制器中重置此变量,我希望由控制者自动完成。

非常感谢你。

2 个答案:

答案 0 :(得分:0)

向根作用域添加一个事件监听器,然后执行您想要的操作

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

答案 1 :(得分:0)

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

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

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