繁体   English   中英

从 AngularJS 访问全局变量

[英]Access global variable from AngularJS

我想用嵌入在 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>

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

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

但它不起作用。

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

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

至少有两种方式:

  1. 在独立脚本标签中声明tags数组,在这种情况下, tags变量将绑定到窗口对象。 将 $window 注入您的控制器以访问您的窗口绑定变量。
  2. ng-init指令中声明你的tags数组。

显示两种解决方案:

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;
    }
  ]
);

普林克

我强烈建议不要污染 window 对象。

暂无
暂无

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

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