Step 1: Creating first controller
[javascript]
function SPController($scope) {
//code here..
}
[/javascript]
Created first controller with a name
SPController.
Previously, controller is mentioned as a JavaScript constructor function. A single argument with
$ sign known as scope is passed. Every controller has its particular scope. Scope binds both controller and view.
Step 2: Creating Module
Model is a JavaScript object. It lives within controller. To make model accessible in the view, a
$scope
object is needed.
[javascript]
myApp.controller('SPController', function($scope) {
$scope.users = [
{name:'Smith',age:23},
{name:'Mike',age:24},
{name:'John',age:26},
];
});
[/javascript]
In the above code, a model named ‘
users
’ is created, which is an array of objects.
Step 3: Putting it together into the view
Now, controller is set up and models are defined. To display data to the user, a view has to be created.
[html]
<h1>AngularJS MVC Architecture</h1>
<div ng-controller="SPController">
<ul>
<li ng-repeat="user in users">
{{ (user.name) + ', ' + user.age }}
</li>
</ul>
</div>
[/html]
index.html
[html]
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.3.14" data-semver="1.3.14" src="https://code.angularjs.org/1.3.14/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
<script src="App.js"></script>
<script src="Controller.js"></script>
</head>
<body ng-app="spApp">
<h1>AngularJS MVC Architecture</h1>
<div ng-controller="SPController">
<ul>
<li ng-repeat="user in users">
{{ (user.name) + ', ' + user.age }}
</li>
</ul>
</div>
</body>
</html>
[/html]
App.js
[html]
var myApp = angular.module("spApp", []);
[/html]
Output: