问题
I'm trying to have a bootstraps navbar display and remove html elements defendant on data from an angular controller.
I have the following jade code:
div.navbar.navbar-fixed-top
div.navbar-inner
div.container-fluid(data-ng-controller="NavCtrl")
a.btn.btn-navbar(data-toggle='collapse', data-target='.nav-collapse')
span.icon-bar
span.icon-bar
span.icon-bar
div.nav-collapse.collapse
ul.nav
li
a(href='/topics') Topics
li(ng-show="curUser.admin")
a(href='/users') Users
li(ng-show="curUser.admin")
a(href='/organizations') Organizations
li(ng-show="curUser.admin")
a(href='/topicConfs') TopicConfig
li.divider
ul.nav.pull-right
{{authenticated}}
li.dropdown(ng-show="authenticated")
a.dropdown-toggle(role='button', data-toggle='dropdown', href='#') {{curUser.email}}
b.caret
ul.dropdown-menu(role='menu')
li
a(href='/users/{{curUser._id}}') Profile
li.divider
li
a.btn(ng-click="logout()") Logout
And a controller with the following:
function NavCtrl($location, $scope, $rootScope, CurrentUser){
$scope.curUser = CurrentUser.getUser()
$scope.authenticated = CurrentUser.isAuthenticated()
$rootScope.$on('$routeChangeStart', function(){
$scope.curUser = CurrentUser.getUser()
$scope.authenticated = CurrentUser.isAuthenticated()
})
$scope.logout = function(){
CurrentUser.logout(function(result){
$scope.curUser = CurrentUser.getUser()
$scope.authenticated = CurrentUser.isAuthenticated()
console.log("authenticated before logout is %j", $scope.authenticated)
$location.url('/')
})
}
}
Everything displays properly until the $scope.authenticated
is set to false
and $scope.user
is set to {}
where none of the ng-show attributes are updated in the nav-bar.
What do I need to do to have the bootstraps nav elements respond to the change in the $scope
variables?
回答1:
When Angular $scope properties are changed "outside" of Angular, $scope.$apply()
needs to be called to cause Angular to enter its digest loop. Any properties that are projected onto the current view will have $watches, which the digest loop will evaluate. When a change is detected in one of these $watches, the view is updated.
Examples of "outside" of Angular:
- Browser event callback. E.g.,
element.bind('someEvent', function() {
//need to call scope.$apply in here
})
- Third-party plugin callback. E.g., the callback passed to
logout
above. - Third-party AJAX callback.
- Third-party promise.
来源:https://stackoverflow.com/questions/15672278/angularjs-bootstraps-navbar