我正在写一个anglarjs app:
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变量。我做错了什么?
答案 0 :(得分: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>
答案 1 :(得分: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);}
};
然后在您的控制器中,您可以像这样获取当前标题:
$scope.currentTitle = WorkService.getCurrentTitle;
请注意,您将其设置为等于getCurrentTitle函数本身(不是函数的结果)。
现在你的html看起来像这样:
<h1 ng-bind-html="currentTitle()"></h1>
无需设置$ watch或挂起$ rootScope的东西。请在此处查看Demo。