星期二, 4月 29, 2014

[AngularJS] 如何在AngularJS中存取全域變數

如果你有一個需求想要在Controller中存取全域的javascript變數,
可以透過$windowng-init directive二種方法,
最後回應的作者建議$window來存取全域的js變數

 可參考此篇說明: http://stackoverflow.com/questions/15275160/access-global-variable-from-angularjs

以下是擷錄內容:

There are at least two ways:

  • 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.
  • Declare your tags array inside the ng-init directive.

Showing both solutions:

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

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails