AngularJS - MVC Architecture

Majority of javascript developers use AngularJs MVC pattern, because its offers architectural benefits over standard javascript. It decouples the model and view which leads to effortless maintenance in the project.


Model

Model represents the current state of the application data. Model is primarily concerned with business data. Model consistently notifies its observers (e.g views) that a change has occurred so that views reacts accordingly.

For Example: Lets consider there is a model that holds the value for a dropdown list on the page. Once the model is updated it notifies the dropdown to show the new set of values.

View

View is a visual representation of current state of the model. A view consistently observes the model and once the model notifies a change, it reacts accordingly. View is a DOM element which interacts with the users.

Controller

In Angular, controller is a Javascript function which controls the models and views. Controller has two parts i.e state ($scope variable) and behavior ($scope function). Controller is attached to the DOM via the ng-controller directive.

Controller runs only once during the page load. After that a hook is created between View (DOM) and Model ($scope variable/ $scope function). Once the view is updated all the hooked functions for the respective controller are executed. A page can have more than one controller. It can be associated to any DOM element like div,p,input,label.

Sample code for above output

<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<body ng-app="employeeApp"> 
 <div ng-controller="pfController">
  Please Enter Your Basic Pay : <input ng-model="basicAmount" type="text"/>
  <p ng-bind="pf"></p>
  <p ng-bind="epf"></p>
  <p class="ng-cloak">{{ pfAmount() }}</p>
 </div>
</body>
<script>
var employeeApp = angular.module("employeeApp",[]);
 employeeApp.controller("pfController",function($scope){ 
 /* scope varibales */
 $scope.basicAmount = 0;$scope.pf='';$scope.epf='';
 
 /* scope function - Below function will call when 
 you trying to change the value in basic Pay textbox */
 
 $scope.pfAmount = function(){
  $scope.pf  = "PF Amount for Your Basic Pay  : "+($scope.basicAmount*12)/100;
  $scope.epf = "EPF Amount for Your Basic Pay : "+($scope.basicAmount*12)/100;
  return "Above Calculation is 12% of Basic Pay";
 };
});
</script>

Previous Topic : AngularJS Basics Directives