Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS : accessing global variable within html template

I am writing an angularJs app:

html :

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

</div>

I am searching for a way to update the currentTitle variable in my html which is in global scope.

.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;

          })

})

But currentTitle variable is not updated in the template. What am i doing wrong?

like image 808
ratata Avatar asked Mar 19 '23 11:03

ratata


1 Answers

When you do WorkService.currentTitle = data.title current scope is unaware of this change. That is why you wont see the change in the template.

It is not ideal but for this requirement you may keep the currentTitle in $rootScope and keep update $scope.currentTitle in each controllers and that will do.

.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;

          })

})

And in html

<h1 ng-bind-html="globalData.currentTitle"></h1>
like image 74
Mathews Avatar answered Apr 01 '23 18:04

Mathews