加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 使用$rootscope显示和隐藏

发布时间:2020-12-17 10:23:07 所属栏目:安全 来源:网络整理
导读:我的index.html模板中有一个搜索栏,我需要在某些页面上隐藏它.我正在使用ui-router和$state. 我可以完成这项工作的唯一方法是将$rootscope注入到我的所有控制器中以进行ng-hide:true或false以在需要的地方打开或关闭它们. (我只需要隐藏在1或2页上) 我不认
我的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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读