笨蛋:http://plnkr.co/edit/0efF1Av4lhZFGamxKzaO?p=preview
下面是我的标题,有一个 ng-show="cornerLogo"
我只想在关于、登录和注册 View 上设置为 true
,但是false
主页 View 。
<body id="body_id"
ng-app="myApp"
ng-controller="HomeCtrl">
<header>
<section ng-show="cornerLogo">
<h1><a href="index.html">Logo</a></h1>
</section>
<nav id="main_nav">
<ul>
<li><a ui-sref="about">About</a></li>
<li><a ui-sref="login">Sign In</a></li>
<li><a ui-sref="register">Create Account</a></li>
</ul>
</nav>
</header>
<ui-view></ui-view>
所以它在我的 HomeCtrl 中工作,因为它是页面上的主 Controller 。
var app = angular.module('app-home', [])
.controller('HomeCtrl', ['$scope', function($scope) {
$scope.cornerLogo = false;
}]);
但是,当我切换到关于、登录或注册 View 时,我丢失了 $scope
有没有办法在我的 stateProvider 的某处为 ui-router 设置一个全局变量?否则,您将如何处理这个问题?
var app = angular.module('bitAge',
['ui.router',
'app-header',
'app-home',
'app-about',
'app-login',
'app-register'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '_views/home.html',
controller: 'HomeCtrl',
})
.state('about', {
url: '/about',
templateUrl: '_views/about.html',
controller: 'AboutCtrl'
})
.state('login', {
url: '/login',
templateUrl: '_views/login.html',
controller: 'LoginCtrl'
})
.state('register', {
url: '/register',
templateUrl: '_views/register.html',
controller: 'RegisterCtrl'
});
// default view:
$urlRouterProvider.otherwise('/home');
}]);
最佳答案
除了我在问题中的评论之外,要解决您的问题,您可以采用这种方法。
您在 home
部分的状态注册中将 HomeCtrl
指定为绑定(bind) Controller 。因此,改为为您的应用程序创建一个主 Controller 。这样您就可以将责任分开。注入(inject) $state
并公开一个名为 hideLogo
的方法,并使用 $state.is
确定显示/隐藏 Logo 的逻辑。
即:
var app = angular.module('app-home')
.controller('MainCtrl', ['$scope', '$state', function($scope, $state) {
$scope.hideLogo = function(){
return $state.is('home');
}
}]);
在索引 html 中,使用 MainCtrl
作为应用程序的主 Controller 。
<body ng-app="myApp" ng-controller="MainCtrl">
<header>
<section
ng-hide="hideLogo()">
<h1><a href="index.html">Corner Logo</a></h1>
</section>
如果您想直接在 View 上使用$state
,您需要将它注入(inject)到MainCtrlland 中,在$scope 对象上设置$state,以便您可以直接使用它。尽管我强烈建议不要使用此技术,但您不应在范围对象中并最终在 View 中公开状态。仅公开 View 模型中需要的内容。
即在 MainCtrl 中:
var app = angular.module('app-home')
.controller('MainCtrl', ['$scope', '$state', function($scope, $state) {
$scope.$state= $state;
}]);
并在 View 中使用它:
<section
ng-hide="$state.is('home')">
关于javascript - 如何通过不同的 View / Controller 在特定元素上设置 ng-show?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28036817/