2

I am learning angular and I am from jQuery background and facing problem to get hold on angular. so i often stumble to understand many things in angular code.

Just seen the code below and I do not understand what scope is doing in below directives?

But if I remove the scope from below directive then what will not work? so please help me to understand the usage of scope and its importance with a example if possible. Thanks

<li my-directive price="item.price" ng-repeat="item in products">{{item.name}} &mdash; {{item.price}}</li>

    myApp.directive('myDirective', function(){
      return {
        scope: { price: '=' },
        require: 'ngModel',
        link : function(scope){
          console.log(scope.price)
        },
        controller: function(scope, element, attrs, ngModel){
          console.log(ngModel.price);
          console.log(scope.price);
        }
      }
    });
shershen
  • 9,875
  • 11
  • 39
  • 60
Mou
  • 15,673
  • 43
  • 156
  • 275
  • 1
    I'd highly recommend you to read up [angular docs](https://docs.angularjs.org/guide/scope), it is already well explained. – Pankaj Parkar Apr 09 '16 at 18:55

2 Answers2

3

In that sample you have scope: { price: '=' }, states that internal scope variable price of the directive is exactly binded to parent's scope. It has access to it and i value changes in parent scope, directive's value of price will change as well.

Remove this line from your directive scope: { ... } and then your directive will not create a new scope. But it will still work - meaning it won't create an error. There are use cases when you need or need not to have isolated scopes.

To figure out better how things work with angular and scopes - please check the following great resources:

  1. angular vs jQuery - "Thinking in AngularJS" if I have a jQuery background?
  2. $scope itself in angular - How does data binding work in AngularJS?
  3. various types of scope variables in directives - What is the difference between '@' and '=' in directive scope in AngularJS?
Community
  • 1
  • 1
shershen
  • 9,875
  • 11
  • 39
  • 60
1

If you don't mention the scope configuration object your directive will use is parent's scope, but when you mention the scope object it creates its own isolated scope.

So if you don't mention the scope object you will have access to variables from your parent controller directly.

ref : http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/

aman verma
  • 11
  • 2
  • when isolated scope is required in directive? looking for a right example code which explain the importance of isolated scope. – Mou Apr 09 '16 at 19:49
  • if we change the value in isolated scope then changes will be reflected in controller scope ? – Mou Apr 11 '16 at 19:56