javascript 从 AngularJS 访问全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15275160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:08:56  来源:igfitidea点击:

Access global variable from AngularJS

javascriptjsonangularjs

提问by deamon

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

我想用嵌入在 HTML 页面中的 JSON 对象初始化 Angular 模型。例子:

<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 tagsfield cannot be resolved, because it is looked up in the $scope. I tried to access the tagsfield in my controller like this:

tags字段无法解析,因为它在$scope. 我尝试tags像这样访问控制器中的字段:

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

But it doesn't work.

但它不起作用。

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

仅当我将TagList直接包含在 HTML 页面中并将 json 直接呈现到此函数中时,它才有效。

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

如何tags在 Angular 控制器中访问单独的 js 文件中的字段?

回答by Stewie

There are at least two ways:

至少有两种方式:

  1. Declare your tagsarray in a standalone script tags, in which case your tagsvariable will be bound to window object. Inject $window into your controller to access your window-bound variables.
  2. Declare your tagsarray inside the ng-initdirective.
  1. tags在独立脚本标签中声明您的数组,在这种情况下,您的tags变量将绑定到 window 对象。将 $window 注入您的控制器以访问您的窗口绑定变量。
  2. tagsng-init指令中声明您的数组。

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 对象。