X
    Categories: Angularjs

AngularJS Scopes Tutorial With Example

Scope is an object that refers to the application model. It is an execution context for expressions. Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events.

1. What are Scopes?

Before we get into Controllers let us understand Scopes. Scope is nothing but an object that Glues the View with Controller. They hold the Model data that we need to pass to view. Scope uses Angular’s two-way data binding to bind model data to view.

Imaging $scope as an object that links Controller to the View. It is controllers responsibility to initialize the data that the view needs to display. This is done by making changes to $scope.

Let us see a small Hello World application to understand $scope.

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<div ng-app="" ng-controller="ContactController">
    
    Email:<input type="text" ng-model="newcontact" />
    
    <button ng-click="add()">Add</button>
    
    <h2>Contacts</h2>
    <ul style="list-style-type:none;">
		<li ng-repeat="contact in contacts"> {{ contact }} </li>
	</ul>
    
</div>
<script> 
function ContactController($scope) {
    $scope.contacts = ["muthu0807@gmail.com", "hello@hotmail.com"];
    
    $scope.add = function() {
        $scope.contacts.push($scope.newcontact);
		$scope.newcontact = "";
    }
}
</script>

 

 

1.2. ng-controller

1. By using ng-controller call ContactController in div

2. Whatever inside div ContactController will influence it.

3. The object $scope which we pass as an argument. This object is used to bind the controller with view

4.  When AngularJS initialize this controller, it automatically creates and injects the $scope object to this function using dependency injection.

1.2. ng-repeat

1. ng-repeat will used to display the array variables in loop.


2. ngRepeat is on most common angular attribute to bind the data into the view.

3. We used contacts in contact, contact is user defined variable and contacts is in $scope array.

4. By using binding operator $scope created array called contacts

$scope.contacts = ["hi@email.com", "hello@email.com"]

1.2. ng-click

1. ng-click is in one of the attribute which act like an jquery onclik function.

2. Here we called like ng-click = “add()”, in this case it will pass the function to ContactController -> add()  function

3. We will define the function like $scope.function_name().

4. we have written $scopes.contact.push($scope.newcontact);

4.1 Contact is an array, Push will append the value into the array, $scope.newcontact will automatically take textbox value.

Email:<input type="text" ng-model="newcontact" />

 5. {{ contact }} will display the result. contact is an user defined variable.

 

Thanks!. If you like this article don’t forget to share and comment.

 

Marimuthu: