ott*_*tz0 5 angularjs angular-ui-router 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;
}
});
Run Code Online (Sandbox Code Playgroud)
现在,在您的中index.html,只需使用ng-show:
<div ng-show="globalData.showSearchBar">
<input type="text" ng-model="query" />
</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2091 次 |
| 最近记录: |