Monday, March 28, 2016

Difference between "=", "@" and "&" - Angular JS


All three bindings are ways of passing data from your parent scope to your directive's isolated scope through the element's attributes:
  1. @ binding is for passing strings. These strings support {{}} expressions for interpolated values. For example: . The interpolated expression is evaluated against directive's parent scope.
  2. = binding is for two-way model binding. The model in parent scope is linked to the model in the directive's isolated scope. Changes to one model affects the other, and vice versa.
  3. & binding is for passing a method into your directive's scope so that it can be called within your directive. The method is pre-bound to the directive's parent scope, and supports arguments. For example if the method is hello(name) in parent scope, then in order to execute the method from inside your directive, you must call $scope.hello({name:'world'})
I find that it's easier to remember these differences by referring to the scope bindings by a shorter description:
  • @ Attribute string binding
  • = Two-way model binding
  • & Callback method binding
The symbols also make it clearer as to what the scope variable represents inside of your directive's implementation:
  • @ string
  • = model
  • & method
In order of usefulness (for me anyways):
  1. =
  2. @
  3. &

There are three ways scope can be added in the directive:
  1. Parent scope: This is the default scope inheritance.
The directive and its parent(controller/directive inside which it lies) scope is same. So any changes made to the scope variables inside directive are reflected in the parent controller as well. You don't need to specify this as it is default.
  1. Child scope: directive creates a child scope which inherits from the parent scope if you specify the scope variable of the directive as true.
Here, if you change the scope variables inside directive, it wont reflect in the parent scope, but if you change the property of a scope variable, that is reflected in the parent scope, as you actually modified the scope variable of the parent.
Example,
app.directive("myDirective", function(){

    return {
        restrict: "EA",
        scope: true,
        link: function(element, scope, attrs){
            scope.somvar = "new value"; //doesnot reflect in the parent scope
            scope.someObj.someProp = "new value"; //reflects as someObj is of parent, we modified that but did not override.
        }
    };
});
  1. Isolated scope: This is used when you want to create scope that does not inherit from the controller scope.
This happens when you are creating plugins as this makes the directive generic, since it can be placed in any html and does not gets affected by its parent scope.
Now, if you dont want any interaction with the parent scope, then you can just specify scope as empty object. like,
scope: {} //this does not interact with the parent scope in any way
Mostly this is not the case as we need some interaction with the parent scope, so we want some of the values/ changes to pass through. For this reason we use:
1. "@"   (  Text binding / one-way binding )
2. "="   ( Direct model binding / two-way binding )
3. "&"   ( Behaviour binding / Method binding  )
@ means that the changes from the controller scope will be reflected in the directive scope but if you modify the value in the directive scope, the controller scope variable will not get affected.
@ always expects the mapped attribute to be an expression. This is very important; because to make the “@” prefix work, we need to wrap the attribute value inside {{}}.
= is birectional so if you change the variable in directive scope, the controller scope variable gets affected as well
& is used to bind controller scope method so that if needed we can call it from the directive
Advantage here is that, the name of variable need not be same in controller scope and directive scope.
Example, directive scope has a variable "dirVar" which syncs with variable "contVar" of the controller scope. This gives a lot of power and generalisation to the directive as one controller can sync with variable v1 while another controller using the same directive can ask dirVar to sync with variable v2.
Below is the example of usage:
The directive and controller are:
 var app = angular.module("app", []);
 app.controller("MainCtrl", function( $scope ){
    $scope.name = "Harry";
    $scope.color = "#333333";
    $scope.reverseName = function(){
     $scope.name = $scope.name.split("").reverse().join("");
    };
    $scope.randomColor = function(){
        $scope.color = '#'+Math.floor(Math.random()*16777215).toString(16);
    };
});
app.directive("myDirective", function(){
    return {
        restrict: "EA",
        scope: {
            name: "@",
            color: "=",
            reverse: "&"
        },
        link: function(element, scope, attrs){
           //do something like
           $scope.reverse(); 
          //calling the controllers function
        }
    };
});
And the html(note the differnce for @ and =):
<div my-directive
  class="directive"
  name="{{name}}"
  reverse="reverseName()"
  color="color" >
</div>