最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using variables in ng-repeat - Stack Overflow

programmeradmin2浏览0评论

How can I use variable inside ng-repeat, if it is defined outside Angular.js directive?

For example, this doesn't work:

<script>
var items = ['a', 'b', 'c'];
</script>

<div ng-repeat="n in items">
...
</div>

<script>
... do something with items ...
</script>

How to make a variable work both inside ng-repeat scope and outside it?

(Obviously I am not ninja in Angular :) )

How can I use variable inside ng-repeat, if it is defined outside Angular.js directive?

For example, this doesn't work:

<script>
var items = ['a', 'b', 'c'];
</script>

<div ng-repeat="n in items">
...
</div>

<script>
... do something with items ...
</script>

How to make a variable work both inside ng-repeat scope and outside it?

(Obviously I am not ninja in Angular :) )

Share Improve this question asked May 28, 2015 at 9:54 cincplugcincplug 1,0545 gold badges22 silver badges39 bronze badges 2
  • You can add another ng-repeat directive, but notice that items is a global variable, so you can acess to it wherever you need in your page – Pablo Lozano Commented May 28, 2015 at 9:57
  • What variable do you want to use n or items? – Pavlo Commented May 28, 2015 at 10:02
Add a ment  | 

2 Answers 2

Reset to default 5

If you define items like that, it is put on the global scope (in a browser environment, the window object).

The ng-repeat directive can only access variables on the scope of its controller. So you need to do something like this:

$scope.items = items;

while initializing your controller.

There are two methods, either:

  1. declare the items variable within a scope of controller. For e.g:

    myapp.controller('testCtrl', ['$scope',function($scope) {
     $scope.items = ['a', 'b', 'c']
    }]);
    

    and then use this controller like this:

    <body ng-controller="testCtrl"> 
     <div ng-repeat="n in items">
      <!--your html here-->
     </div>
    </body>
    
  2. or you can init it directly inside html like this:

    <body ng-controller="testCtrl" ng-init="items = ['a', 'b', 'c']"> 
     <div ng-repeat="n in items">
      <!--your html here-->
     </div>
    </body>
    
发布评论

评论列表(0)

  1. 暂无评论