Directive scope binding in Angular.js
Scope in a Directive-All directives have a scope in association with it. THe controller and link functions, AngularJS controller functions and variables are accessed using the scope object. A directive is defined in a controller and by default directives do not create new scope instead they use scope of parent controller. Default scope can be changed using the scope field of the data definition object. The value of the field defines how it will be created and used, the values can be ’true’, ’false’ and ‘{}’. If the scope is false the directive is using the scope of the parent controller.
If the scope field is true the directive uses its own scope created by Angular by inheriting from parent. If the value is ‘{}’ the directive gets isolated scope. In this case the scope of directive is not inherited from the parent and we pass objects for the scope field. In isolated scope the scope has prefixes and they are:
@ - Text binding or one way binding
= - Direct binding or two way binding
& - Behavior binding or method binding.
Here is an example of scope field value as false.
Creating an Angular app and controller
var movieApp = angular.module("movieApp",[]); movieApp.controller("movieController",function($scope){ $scope.movie = "Ice Age"; });
Then define the directive.
movieApp.directive("movieDirective", function(){
return {
restrict: "E",
scope: false,
template: "<div>Movie title : {{movie}}</div>"+
"Type a new movie title : <input type='text' ng-model='movie' />"
};
});
In the final step we embed the directive in HTML.
<div ng-app="movieApp">
<div ng-controller="movieController">
<h2>Movie: {{movie}}</h2>
Change Movie Title : <input type='text' ng-model='movie'/>
<movie-directive></movie-directive>
</div>
</div>
In the HTML snippet the movie name takes value from the controller's scope. Movie title in the directive template also gets its value from the controller scope. Here the directive does not create its own scope but uses parent scope. So any changes made to movie title in directive template changes movie title in header tag in HTML and vice versa.
sam smith
16 Apr 2023
I just want the whole world to know about this spell caster I met two weeks ago, I cannot say everything he has done for me my wife left me 3 years ago left with my kids I was going through online when I meant this wonderful man's testimony online I decided to give it a try and my wife is back to me now and we are happily married again cause is too much to put in writing all I can say is thank you very much am very happy Contact him today on oseremenspelltemple@gmail.com or whatsapp him on +2348136482342. www.facebook.com/Dr-odion-spell-temple-110513923938220