angularjs – 使用$rootscope显示和隐藏

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

我可以完成这项工作的唯一方法是将$rootscope注入到我的所有控制器中以进行ng-hide:true或false以在需要的地方打开或关闭它们. (我只需要隐藏在1或2页上)

我不认为这是正确的方法,因为我的所有控制器现在都依赖并注入$rootscope.

还有另一种方法吗?

让我们从全局控制器示例GlobalCtrl开始,它添加到body或html标签中,如ng-controller =“GlobalCtrl”.

这样做将使我们能够在整个单页Angular应用程序中保持此GlobalCtrl的范围(因为您使用的是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>

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...