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
oritems
? – Pavlo Commented May 28, 2015 at 10:02
2 Answers
Reset to default 5If 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:
declare the
items
variable within ascope
ofcontroller
. 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>
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>