简体   繁体   English

从 AngularJS 访问全局变量

[英]Access global variable from AngularJS

I want to initialize a Angular model with a JSON object which is embedded in a HTML page.我想用嵌入在 HTML 页面中的 JSON 对象初始化 Angular 模型。 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 . tags字段无法解析,因为它是在$scope查找的。 I tried to access the tags field in my controller like this:我尝试像这样访问控制器中的tags字段:

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.仅当我将TagList直接包含在 HTML 页面中并将 JSON 直接呈现到此函数中时,它才有效。

How can I access the tags field in a separate js file in a Angular controller?如何访问 Angular 控制器中单独 js 文件中的tags字段?

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.在独立脚本标签中声明tags数组,在这种情况下, tags变量将绑定到窗口对象。 Inject $window into your controller to access your window-bound variables.将 $window 注入您的控制器以访问您的窗口绑定变量。
  2. Declare your tags array inside the ng-init directive.ng-init指令中声明你的tags数组。

Showing both solutions:显示两种解决方案:

HTML: 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: JS:

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

Plnkr普林克

I strongly advise against polluting window object.我强烈建议不要污染 window 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM