user6680 user6680 - 5 months ago 14
AngularJS Question

ng-controller won't output variables

I'm still very new at this and I'm having issues getting the variables to output from the controller. I'm not sure what i'm doing wrong. Any suggestions. Currently the webpage is just blank with no text except Hello World, which is outside of the controller. If I put it within the controller div it disappears too.

index.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="myFirstApp">
{{"Hello World"}}
<div ng-controller="mainController as ctrl">
<div class="bookListing" ng-repeat="book in ctrl.books">
{{book.title}}
{{book.author}}
{{book.date}}
</div>
</div>
</body>
</html>


app.js

var app = angular.module('myFirstApp', []);


app.controller('mainController', function(){
var books = [
{
title: "Title 1",
author: "Joe Bob",
date: new Date("2966", "04", "20")
},
{
title: "Title 2",
author: "Bob Joe",
date: new Date("2205", "06", "20")
},
{
title: "Title 3",
author: "Susie Joe",
date: new Date("2222", "09", "20")

}
];

});

Answer

var books is a local variable. In order to pass it to view you need to make it a property of the controller

var vm = this;
vm.books = [.....];

In the view ctrl is the equivalent of this in the controller

Comments