Gaurav Aggarwal Gaurav Aggarwal - 6 months ago 14
AngularJS Question

How X is getting value in angularJS

I am new to angular.js just working on a function

ng-repeat
. in which i am using
ng-repeat="x in name"
where i have defines some values in
names
but i didn't defines x anywhere in complete code.

Here is my code:

<div ng-app="myApp" ng-controller="namesCtrl">

<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}
];
});
</script>


Everything is working fine but i wonder how the values are coming in
x
or what exactly
ng-repeat
is doing here as i am just calling
x
but not defining any value in
x
.

Answer

x is being defined by angular's ng-repeat directive. It is iterating over all the values in names and binding each value to x in turn.

Note that you can choose any other valid variable name instead of x.

The reason there is no conflict between each value of x is that each iteration gets its own $scope.

See also the ng-repeat documentation.

Comments