gpt4 book ai didi

angularjs - 使用 $rootscope 显示和隐藏

转载 作者:行者123 更新时间:2023-12-04 20:36:40 24 4
gpt4 key购买 nike

我的 index.html 中有一个搜索栏我需要在某些页面上隐藏的模板。我正在使用 ui-router$state .

我能完成这项工作的唯一方法是注入(inject) $rootscope进入我所有的 Controller 到ng-hide: truefalse在需要的地方打开或关闭它们。 (我真的只需要隐藏在 1 或 2 页上)

我认为这不是正确的方法,因为我所有的 Controller 现在都依赖并注入(inject)到 $rootscope 上。 .

还有另一种方法可以做到这一点吗?

最佳答案

让我们从一个全局 Controller 示例开始 GlobalCtrl添加到 bodyhtml标签喜欢 ng-controller="GlobalCtrl .

这样做将使我们能够保持 GlobalCtrl 的范围。在您的单页 Angular 应用程序中(当您使用 ui-router 时),我们可以避免使用 $rootScope (实际上是模仿 $rootScope 的用法)。

现在,在您的 GlobalCtrl 内定义这样的东西:

// Using an object to avoid the scope inheritance problem of Angular
// https://github.com/angular/angular.js/wiki/Understanding-Scopes
$scope.globalData = {showSearchBar: true};

// This callback will be called everytime you change a page using ui-router state
$scope.$on('$stateChangeStart', function(event, toState, toParams) {
$scope.globalData.showSearchBar = true;

// Just check for your page where you do not want to display the search bar
// I'm using just an example like I don't want to display in contac-us page named state
if (toState.name == 'contact-us' || toParams.foo == "bar") {
$scope.globalData.showSearchBar = false;
}
});

现在,在您的 index.html , 只需使用 ng-show :
<div ng-show="globalData.showSearchBar">
<input type="text" ng-model="query" />
</div>

关于angularjs - 使用 $rootscope 显示和隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34203464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com