从AngularJS访问全局变量 [英] Access global variable from AngularJS

查看:419
本文介绍了从AngularJS访问全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要初始化一个角模型JSON对象至极嵌入在HTML页面。例如:

I want to initialize a Angular model with a JSON object wich 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.

它的工作原理只有当我包括标记列表直接插入HTML页面,并渲染JSON直接进入此功能。

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

我如何访问标记在一个单独的js文件字段和角度控制?

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

推荐答案

有至少两种方式:


  1. 定义你的标记阵列在一个独立的脚本标签,在这种情况下,你的标记变量将被绑定到窗口目的。注$窗口到控制器来访问你的窗口绑定变量。

  2. 声明你的标记 NG-INIT 指令内的数组。

  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.

显示这两种解决方案:

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.

这篇关于从AngularJS访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆