您好我想知道重置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
中出现,我该怎么做?
而且我不想在每个控制器中重置此变量,我希望由控制者自动完成。
非常感谢你。
答案 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 = {};
}
};
});
从这里注入和请求每个控制器。