user6680 user6680 - 5 months ago 29
AngularJS Question

Angular Arrays not outputting to screen

I created an object called reveiws and I'm trying to get it to appear on the screen. When I put ng-repeat="rev in reviews" in div id reviews nothing appears at all on the screen. It's blank except for the word Hello. Also there are no console errors. If I remove that line

ng-repeat="rev in reviews"
and keep it as
<div id="reviews" ng-controller="mainController as ctrl">

Then it appears as

Hello
{{rev.name}} {{"HI"}}


so the code is only affected in the controller since Hello, which is outside of the controller outputted correctly. Why is the array not outputting the name?

index.html

<html ng-app="objectTest" xmlns="http://www.w3.org/1999/xhtml">
<head>

<title></title>
</head>

<body>
{{"Hello"}}

<div id="reviews" ng-controller="mainController as ctrl" ng-repeat="rev in reviews">
{{rev.name}} {{"HI"}}
</div><script src="bower_components/angular/angular.js" type="text/javascript">
</script><script src="app.js" type="text/javascript">
</script>
</body>
</html>


app.js

var app = angular.module('objectTest', [])
.controller('mainController'['$scope' , function($scope){
$scope.reviews = [
{
name: "Joe Smith",
description: "It works!"

},
{
name: "Bill Smith",
description: "great site"
}
];


}]);

Answer

It will work if you remove the "as" syntax when you define the controller in the view.

Change ng-controller="mainController as ctrl" to ng-controller="mainController".

Updated: added working code

var app = angular.module('objectTest', [])
    .controller('mainController', ['$scope' , function($scope){
    $scope.reviews = [
    {
    name: "Joe Smith",
    description: "It works!"

    },
{
  name: "Bill Smith",
 description: "great site"
}
    ];


    }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="objectTest" ng-controller="mainController">
  <div ng-repeat="rev in reviews">
    {{ rev.name }}
  </div>
</div>