AngularJS Scope Tutorial


      As we already know, Angular JS consists of Model, View and Controller

View - it is the HTML portion
Controller - Controllers are javascript functions that controls the data of AngularJS applications
Model  - is data of AngularJS applcation

So, Scope is Model in AngularJS

     Scope in AngularJS is like a bridge between controller and view and you need scope every time you create a controller. Scope is nothing but a Javascript object. Scope is available for both View and Controller.  

Lets see this with an example that will give a clean picture of what we are talking theoretically..

AngularJSScope.html

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
<p>My Name is <b>{{name}}</b></p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name= "Rob";
});
</script>

</body>
</html>

Lets see this code as Model, View and Controller

Controller
     Controller is nothing but a Javascript function. Every controller should have scope - $scope. The scope is a JavaScript object with properties and methods, which are available for both the view and the controller.

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.name= "Rob";
});
</script>

View
     View is what displays your data. So the property from controller is displayed here
<div ng-app="myApp" ng-controller="myCtrl">
<p>My Name is <b>{{name}}</b></p>
</div>

Model
$scope.name= "Rob";

scope is the model.

Output of the program

My Name is Rob

Hope this tutorial helps you to understand the below stuff :
  • Scope in AngularJS
  • Relating model scope AngularJS





Reactions:

0 comments :

Post a Comment