Angularjs Examples

AJS Examples


AngularJS MVC Architecture

MVC stands for Model View Controller which is very popular design pattern in web world. It helps you to organise your application in three different layers and isolate the business logic from its presentation.

  • Model - represent current state and data of your application
  • View - responsible to display/show the data
  • Controller - responsible to controls the relation between Models and Views.

Now let's understand how these three component works in AngularJS MVC Architecture step by step.

Model

in AngularJS, model consists of all premitive data type such as integer, string and boolean and complex type in form of object. In simple word model is just a plain javascript object. But you can build your model from any database like Sql Server or Mysql or from JSON file. In below given syntax $scope is an object, customer is variable which is added to scope object.

Syntax

<script>
    $scope.customer =  {
         'Name'    :   'Jimi',
         'Address' :   '12-13-283/A1',
         'Email'   :   'jimi@yahoo.com'
     }
</script>

View

in AngularJS, view is the DOM elements which is used to display data. To display data from controller, use expression in view. Since AngularJS supports two-way data binding any changes in model data, view will update automatically.

Syntax

<script>
<p> {{customer.name}} </p>
<p> {{customer.address}} </p>
<p> {{customer.name}} </p>
</script>

Controller

in AngularJS, controller provide great control over view and model in order to fatch the data as per request and display in the view. Most important thing here is your model is lives inside the controller.

Syntax

<script>
function RealCustomer($scope){
}
</script>

AngularJS MVC Example

<html ng-app="yourApp">
<head>
<title>My first AngularJS MVC Architecture code</title>
<script SRC="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.js">
</script>
<script type="text/javascript">
//Creating controller here
var app = angular.module('yourApp', []);
    app.controller('realCustomer', function($scope) {
    //Creating model here
    $scope.customer =  {
         'Name'    :   'Jimi',
         'Address' :   '12-13-283/A1',
         'Email'   :   'jimi@yahoo.com'
     }
    });
</script>
</head>
<body>
<p>Displing model data in view through controller</p>
<div ng-controller="realCustomer">
<h3>{{ customer.Name }} </h3>
<h3>{{ customer.Address }} </h3>
<h3>{{ customer.Email }} </h3>
</div>
</body>
</html>