I'm still very basic with AngularJS (and programming in general honestly speaking. Having watched some videos online, I'm trying to understand the controller concept with the below example (e.g. passing an array and then iterating through it with ng-repeat). Have gone over this for the past hour and it works without the controller (e.g. with the array), but not when adding the array in a seperate script. Can anyone help me find my error in logic here - it literally is the same as the video, but I cannot see the error (or even a typo) and feel this is so fundamental, I should have this working, before moving on to the next steps.
Many thanks for any of your help:
<html ng-app>
<head><title>My First Page</title></head>
<body >
<div class="container" ng-controller="SimpleController">
Name:
<br />
<input type="text" ng-model="name" />
<br />
<ul>
<li ng-repeat="cust in customers"> {{ cust.name }} </li>
</ul>
</div>
<script src="script/angular.min.js"></script>
<script>
function SimpleController($scope) {
$scope.customers = [
{ name: 'Simon', lastname: 'Test' },
{ name: 'Thomas', lastname: 'Testi' },
{ name: 'Adi', lastname: 'Testo' },
{ name: 'Adrian', lastname: 'Testo' },
{ name: 'Tomeli', lastname: 'Testi' }
];
}
</script>
</body>
</html>
You are using global declaration of controller which is with angular 1.1 version. If you use version above 1.3 , you should declare the controller as follows,
var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope){
$scope.customers = [
{ name: 'Simon', lastname: 'Test' },
{ name: 'Thomas', lastname: 'Testi' },
{ name: 'Adi', lastname: 'Testo' },
{ name: 'Adrian', lastname: 'Testo' },
{ name: 'Tomeli', lastname: 'Testi' }
];
});
DEMO
var app = angular.module('testApp',[]);
app.controller('SimpleController',function($scope){
$scope.customers = [
{ name: 'Simon', lastname: 'Test' },
{ name: 'Thomas', lastname: 'Testi' },
{ name: 'Adi', lastname: 'Testo' },
{ name: 'Adrian', lastname: 'Testo' },
{ name: 'Tomeli', lastname: 'Testi' }
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testApp">
<div class="container" ng-controller="SimpleController">
Name:
<br />
<input type="text" ng-model="name" />
<br />
<ul>
<li ng-repeat="cust in customers"> {{ cust.name }} </li>
</ul>
</div>
</body>