Tuesday, May 19, 2015

MVC in AngularJS

Angular JS supports MVC style of application design. MVC means Model-View-Controller. Lets understands each of this in Angular JS.

Controller

Controller responsibility is to wire up the $scope (which holds your models) to your view. Angular Model lives inside a controller, you use $scope inside a controller as a glue between controller and view.
Controller contains business logic behind the application to decorate the scope with functions and values.

Example : controller creation

var app = angular.module(‘firstApp’, []);
app.controller(‘MyController’, function($scope) {
});
view raw gistfile1.js hosted with ❤ by GitHub

Model

A model in angular can be a primitive type such as string, number, boolean or a complex type such as object. In short model is just a plain javascript object.
Model lives inside a controller.
Scope is an object and models are the properties of a scope

Example : model creation

var app = angular.module(‘firstApp’, []);
app.controller(‘MyController’, function($scope) {
// model called ‘name’ which is a string
$scope.name = “Deepak Sisodiya”;
});
view raw gistfile1.js hosted with ❤ by GitHub
Here name is model of type string and name is the property of $scope object.

View

View is what the users see, in angular view is HTML

Example : view creation

<!DOCTYPE html>
<html ng-app="firstApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-controller="MyController">
<p>Hello {{ name }}</p>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub

Lets combine all components that is Model-View-Controller

<!DOCTYPE html>
<html ng-app="firstApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-controller="MyController">
<p>Hello {{ name }}</p>
<script>
var app = angular.module('firstApp', []);
app.controller('MyController', function($scope) {
$scope.name = "Deepak Sisodiya";
});
</script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub

model contains your data and with the help of $scope in controller, your model data will be available to your view

Link of Model-View-Controller example

Resource
http://mrbool.com/mvc-in-angularjs/28962

2 comments:

  1. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.We are providing AngularJs training in velachery.
    For more details: AngularJs training in velachery

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete