Search code examples
javascriptangularjswebviewangularjs-rootscope

Accessing rootScope variable in template view not working


I know this is possible and have seen many threads on how to do this but I can't figure out what I am doing wrong. My $rootScope variable is not appearing in my template view.

.run(function($ionicPlatform,$state,$rootScope,$q,apiService) {
  $ionicPlatform.ready(function() {

    $rootScope.test = "HELLO ALL" ;

 ...
 ...
}),

.controller('EventCtrl', function($scope,$rootScope,$state,$stateParams) {

}),

And in my EventCtrl webview template:

<div style="color:red;font-weight:bolder;">{{$root.test}}</div>

Yet, HELLO ALL never appears. I have tried simply {{test}} as suggested in some other posts but that too is not working. What am I getting wrong here? No errors are being generated in console.

I also tried the following, in my EventCtrl controller I set:

$scope.globalScope = $rootScope ;

And then in template accessed: {{globalScope.test}} - and it still didn't work.


Solution

  • You can simply use {{ test }}, since $scope inherits from $rootScope

    Check below:

    angular.module("myApp", [])
      .run(function($rootScope) {
        $rootScope.test = "Hello All"
      })
      .controller("myCtrl", function($scope, $rootScope) {})
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
    <div ng-app="myApp" ng-controller="myCtrl">
      <div style="color:red;font-weight:bolder;">{{test}}</div>
    </div>