我正在编写一个angularJs应用程序:

html:

<div ng-controller=NavCtrl>
        <h1 ng-bind-html="currentTitle"></h1>

</div>

我正在寻找一种方法来更新全局范围内的html中的currentTitle变量。
.service('WorkService', [function(){
    return {
          currentTitle : 'dada'
      };

}])

.controller('NavCtrl', function($scope, $location, $http, WorkService) {
  $scope.works = [];
  $http({method: 'GET', url: '/api/v1/work'}). //collects all works
  success(function(data, status, headers, config) {
      $scope.currentTitle = WorkService.currentTitle;
  })
})

.controller('DetailCtrl', function($scope, $routeParams, $http, WorkService) {

        $http({method: 'GET', url: '/api/v1/work/' + $routeParams.workId + '/'}).
          success(function(data, status, headers, config) {
              $scope.activateButton($routeParams.workId);
              WorkService.currentTitle = data.title;

          })

})

但是currentTitle变量不会在模板中更新。我究竟做错了什么?

最佳答案

当您执行WorkService.currentTitle = data.title时,当前作用域不知道此更改。这就是为什么您看不到模板中的更改的原因。

这不是理想的方法,但是对于此要求,您可以将currentTitle保留在$ rootScope中,并在每个 Controller 中保持更新$ scope.currentTitle来完成。

.run(function($rootScope){
$rootScope.globalData = {currentTitle : 'dada'}
})
.controller('NavCtrl', function($scope, $location, $http, WorkService) {
  $scope.works = [];
  $http({method: 'GET', url: '/api/v1/work'}). //collects all works
  success(function(data, status, headers, config) {
      $scope.globalData.currentTitle = 'New title';
  })
})
.controller('DetailCtrl', function($scope, $routeParams, $http, WorkService) {

        $http({method: 'GET', url: '/api/v1/work/' + $routeParams.workId + '/'}).
          success(function(data, status, headers, config) {
              $scope.activateButton($routeParams.workId);
              $scope.globalData.currentTitle  = data.title;

          })

})

和在HTML
<h1 ng-bind-html="globalData.currentTitle"></h1>

09-25 18:47