在Angular.js中刷新特定控制器的最佳方法是什么,我可以检测到这样的页面更改:
//when app runs call this function.
app.run(function($rootScope, $route, $location, $cookies){
//Bind the `$locationChangeSuccess` event on the rootScope, so that we dont need to
//bind in induvidual controllers.
$rootScope.$on('$locationChangeSuccess', function() {
$rootScope.actualLocation = $location.path();
});
$rootScope.$watch(function () {return $location.path()}, function (newLocation, oldLocation) {
if($rootScope.actualLocation === newLocation) {
console.log('user hit back');
if($rootScope.actualLocation=='/'){
//clear cookie
var testing = $cookies.getObject('globals');
$location.path('/');
}
}
});
});
我需要刷新我的navigationController,所以如果用户按下后退按钮或刷新浏览器窗口,它会动态保持其状态。
导航控制器:
nav.js
'use strict';
//app global variable
//this is the controller that handles post requests
//declare services as dependecies $http, $location, custom service apiServiceWeb
app.controller('navigationController', function($scope, $route, $rootScope, $http, $location, $cookies, setCredentials) {
//get what is in the cookie
var cookieValue = setCredentials.getCookie('globals');
console.log($cookies.get('globals'));
//hide menu in certain paths
if ($location.path() == '/' || $location.path() == 'signup') {
$scope.isConnected = true;
} else {
$rootScope.$watch('globals', function() {
//if a currentUser does NOT exist, the hide menu.
if (cookieValue = null) {
$scope.isConnected = true;
} else {
$scope.isConnected = false;
}
});
}
});
index.html
这是观点。
<div ng-controller="navigationController">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" ng-hide="isConnected">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Start Bootstrap</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>
<a href="#">About</a>
</li>
<li>
<a href="#">Services</a>
</li>
<li>
<a href="#">Contact</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
</div>
<div ng-view=""></div>