+-
AngularJS:在html模板中访问全局变量

我正在编写一个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变量不会在模板中更新。我在做什么错?

4
投票

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

这不是理想的方法,但是对于此要求,您可以将currentTitle保留在$ rootScope中,并在每个控制器中保持更新$ 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>
3
投票

您不能双向绑定到服务中的变量,但是可以绑定到访问器函数。更改您的服务以返回getter和setter函数:

.service('WorkService', ['$sce', function($sce){
    var currentTitle= $sce.trustAsHtml('dada');
    return {
      getCurrentTitle: function(){ return currentTitle; },
      setCurrentTitle: function(value){ currentTitle = $sce.trustAsHtml(value);}
    };

然后在您的控制器中,您可以像这样获得currentTitle:

$scope.currentTitle = WorkService.getCurrentTitle;

请注意,您将其设置为等于getCurrentTitle函数本身(而不是函数的结果)。

现在您的html看起来像这样:

<h1 ng-bind-html="currentTitle()"></h1>

无需设置$ watchs或挂起$ rootScope。请参阅Demo。