user5182503
user5182503

Reputation:

How to use variables from controller in ng-repeat in AngularJS

I am just learning AngularJS and want to use in ng-repeat variable from controller (without using scope), but it doesn't work. Could anyone point out my mistake? This is my code:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<select>
    <option ng-repeat="x in myCtrl.names">{{x}}</option>
</select>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    var that = this;
    that.names = ["Emil", "Tobias", "Linus"];
});
</script>
</body>
</html>

Upvotes: 0

Views: 151

Answers (2)

Shaifali Kalia
Shaifali Kalia

Reputation: 11

Instead of using direct controller name, use that name which we mention where the controller name declare in html code using 'as' keyword.

For example:

var app = angular.module('myApp', []);
app.controller('myCtrl', function() {
    var viewData = this;
    viewData.names = ["Emil", "Tobias", "Linus"];
});

<div ng-app="myApp" ng-controller="myCtrl as Ctrl">
    <select>
        <option ng-repeat="x in Ctrl.names">{{x}}</option>
    </select>
</div>

Upvotes: 0

amcquaid
amcquaid

Reputation: 539

Set the variable on the scope.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
     $scope.names = ["Emil", "Tobias", "Linus"];
});

Use variable in the controller

var app = angular.module('myApp', []);
app.controller('myCtrl', function() {
    var self = this;
    self.names = ["Emil", "Tobias", "Linus"];
});
<script src="//unpkg.com/angular/angular.js"></script>

<div ng-app="myApp" ng-controller="myCtrl as myController">
    <select>
        <option ng-repeat="x in myController.names">{{x}}</option>
    </select>
</div>

Upvotes: 0

Related Questions