Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access global variable from AngularJS

I want to initialize a Angular model with a JSON object which is embedded in a HTML page. Example:

<html>
  <body>
    <script type="text/javascript" charset="utf-8">
      var tags = [{"name": "some json"}];
    </script>
    <ul>
      <li ng-repeat="tag in tags">{{tag.name}}</li>
    </ul>
  </body>
</html>

The tags field cannot be resolved, because it is looked up in the $scope. I tried to access the tags field in my controller like this:

function TagList($scope, $rootScope) {
  $scope.tags = $rootScope.tags;
}

But it doesn't work.

It works only if I include the TagList directly into the HTML page and render the JSON directly into this function.

How can I access the tags field in a separate js file in a Angular controller?

like image 788
deamon Avatar asked Mar 07 '13 15:03

deamon


1 Answers

There are at least two ways:

  1. Declare your tags array in a standalone script tags, in which case your tags variable will be bound to window object. Inject $window into your controller to access your window-bound variables.
  2. Declare your tags array inside the ng-init directive.

Showing both solutions:

HTML:

<body>

  <script type="text/javascript" charset="utf-8">
    var tags = [{"name": "some json"}];
  </script>

  <div ng-controller="AppController">
    tags: {{tags | json}}
    <ul>
      <li ng-repeat="tag in tags">{{tag.name}}</li>
    </ul>
  </div>  

  <div>
    <ul ng-init="tags = [{name: 'some json'}]">
      <li ng-repeat="tag in tags">{{tag.name}}</li>
    </ul>
  </div>

</body>

JS:

app.controller('AppController',
  [
    '$scope',
    '$window',
    function($scope, $window) {
      $scope.tags = $window.tags;
    }
  ]
);

Plnkr

I strongly advise against polluting window object.

like image 186
Stewie Avatar answered Oct 05 '22 11:10

Stewie