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

13 浏览
0 Comments

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

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

html:

    

我正在寻找一种方法来更新我的HTML中的currentTitle变量,它是在全局范围内定义的。

.service('WorkService', [function(){
    return {
        currentTitle : 'dada'
    };
}])
.controller('NavCtrl', function($scope, $location, $http, WorkService) {
    $scope.works = [];
    $http({method: 'GET', url: '/api/v1/work'}). //收集所有的作品
    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变量在模板中没有被更新。我做错了什么?

0
0 Comments

在AngularJS中,要在HTML模板中访问全局变量,需要注意作用域的问题。当使用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中,可以使用ng-bind-html指令绑定globalData.currentTitle变量:

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

尽管这种方式不是理想的,但在某些需求下可以使用。需要注意的是,如果不需要在根或全局作用域中存储数据,一般认为这是一种不好的做法。

0
0 Comments

问题的原因是无法在服务中进行双向绑定到一个变量,但可以绑定到一个访问器函数。解决方法是将服务改为返回getter和setter函数,然后在控制器中通过调用getter函数来获取currentTitle的值。最后,在html中使用ng-bind-html指令绑定currentTitle函数。

具体实现如下:

首先,在服务中定义currentTitle变量,并返回getter和setter函数。getter函数用于获取currentTitle的值,setter函数用于设置currentTitle的值。

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

然后,在控制器中通过调用getCurrentTitle函数来获取currentTitle的值,并将其赋给$scope.currentTitle变量。

$scope.currentTitle = WorkService.getCurrentTitle;

最后,在html中使用ng-bind-html指令来绑定currentTitle函数,以显示当前的标题。

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

通过以上的改动,就能够在html模板中访问并显示服务中的全局变量currentTitle的值,而无需设置$watches或在$rootScope上挂载其他属性。

0