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.