簡體   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