Reputation: 13
I'm trying to populate a list within a "Controller as" block, but I cannot seem to get anything to display. I've gotten a minimal example of my idea working with $scope
:
JS:
var app = angular.module('testApp', []);
app.controller('listController', ["$scope", ($scope) => {
$scope.listFiles = ["hello", "world"];
}]);
HTML:
<div ng-app="testApp" ng-controller="listController">
<div class="list-group">
<a class="list-group-item list-group-item-action" ng-repeat="filename in listFiles">{{ filename }}</a>
</div>
</div>
But when I introduce "Controller as", the list does not display:
JS:
var app = angular.module('testApp', []);
app.controller('listController', ["$scope", ($scope) => {
var $ctrl = this;
$ctrl.listFiles = ["hello", "world"];
}]);
HTML:
<div ng-app="testApp" ng-controller="listController as ctrl">
<div class="list-group">
<a class="list-group-item list-group-item-action" ng-repeat="filename in ctrl.listFiles">{{ filename }}</a>
</div>
</div>
I understand that $scope
and this
are different concepts, but I cannot seem to wrap my head around the specifics in this case.
Could this be a result of the scope rules for ng-repeat, or am I missing something obvious?
Upvotes: 1
Views: 525
Reputation: 429
You have used es6 arrow function syntax. Since the browser doesn't support es6 syntax.Either you have to use transpiler(Babel) to compile es6 code to pure javascript.
Try changing this
app.controller('listController', ["$scope", ($scope) => {
With
app.controller('listController', ["$scope", function($scope) {
Upvotes: 1
Reputation: 38191
Here you should not use arrow function
while defining controller function
, this will lead this
to an unexpected context which not belong to controller itself. The solution is using normal function
.
refer the below example and fixed jsfiddle.
var app = angular.module('testApp', []);
app.controller('listController', ["$scope", function($scope) {
var $ctrl = this;
this.listFiles = ["hello", "world"];
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<div ng-app="testApp" ng-controller="listController as ctrl">
<div class="list-group">
<a class="list-group-item list-group-item-action" ng-repeat="filename in ctrl.listFiles">{{ filename }}</a>
</div>
</div>
Upvotes: 2