Friday, October 16, 2015

Angular Recipe: Passing data into your Directive

Angular JS


It's often needed to pass some data into your directive from outside.
By default, directives are restricted to attribute 'A' type and are therefore restrict: 'A' is redundant.
Inside directives, it is best practice to use controller only when you want to share functions with other directives. All other times you should use link.
If a directive is only returning the link function you can write it as just return anonymous function: return function(scope, element, attr) {/*...*/};

Bind the Data to our scope

There are 3 options when binding data to an isolate scope:

  • @ - Attribute string binding;
    Binds a local/directive scope property to the evaluated value of the DOM attribute. So, u can use it with simple string values as well as with evaluated values {{}}
  • = - Two-way model binding;
    Binds a local/directive scope property to a parent scope property. So, u cant' use it with {{}} The binding is bidirectional that allows the local/directive scope and the parent scope to share data.
  • & - Callback method binding.
    Use it if you don't need to share data with the parent, but you just want to call a function defined in the parent scope.

@see details in Keynote: AngularJS Do the custom things


Bind the Data between composite directives

Imagine that you have some product card (or review note) directive which you want to use in any places e.g. create & update form.
He is where advantage of the two way binding with your isolated appears.

  • Separate the product data request from your reusable directive;
  • Request & Receive the data into your parent scope;
  • Create your directive isolated scope;
  • Bind the directive isolated scope value with the outside one;
  • Pass the item from the outside in the custom directive html node;

UseCase1: U have some view that contains the list of item cards.
You request the all items data via some service or $http.get directly in the your view controller. Then you just pass each item data to your item cards isolated scope. Here we are any change via main view immediately reflects in the item card.

card.js

angular.module('myApp')
.directive('myItemCard', function () {
    return {
        restrict: 'E',
        templateUrl: 'templates/my-item-card.html',
        // create the directive own scope
        scope: {
            // two way binding with 'product' passed from the parent scope
            item: '='
        },
        controller: function ($scope) {
            /*card logic*/
        }
    }
});

my-item-card.html

<div class="itemCard">
    <h2>
        {{item.category}} {{item.name}}
        <small>
          <em>(#{{item.id}}<span ng-show="item.available"> by it now</span>)</em>
        </small>
    </h2>
    <blockquote>
       {{item.description}} - <em>{{item.date | date: 'h:mma'}}</em>
    </blockquote>
</div>

index.html

<!--pass current product into the item card directive-->
<div ng-repeat="product in products">
    <my-item-card item="product"></my-item-card> 
</div>

UseCase2: U have some view that contains update form & item card.
You request the item data via some service or $http.get directly in the your view controller. Then you just pass it to your update form & too the item card. Here we are any change via update form immediately reflects in the item card...


Access to parent directive controller

There is possibility to interact with your parent controller directive via require property. IMHO, the using of two-way binding ("=") creates less coupling than following approach:

angular.module('MyApp')
.directive('myNavItem', function() {
return {
    restrict: 'E',
    templateUrl: './templates/directives/my-nav-item.html',
    require: '^myNavBar',
    link: function(scope, element, attrs, myNavBarCtrl) {
       scope.isActive = function() {
           return scope.name == nwNavCtrl.getActiveNav();
       };

      scope.activate = function() {
           nwNavCtrl.setActiveNav(scope.name);
      };
    },
    scope: { name: "@"}
  };
});

my-naw-item.html

<a class="list-item" ng-class="{'active' : isActive()}" ng-click="activate()" ng-href="#/{{name | lowercase}}">{{name}}</a>

see Also


36 comments:

  1. It is nice blog Thank you provide important information and I am searching for the same information to save my time AngularJS Online Training

    ReplyDelete
  2. Nice articel, This article help me very well. Thank you. Also please check my article on my site about What Is Angular?.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Thank you for discussing this very useful article. I heard something new from you. Keep blogging. Angularjs training institute in jalandhar

    ReplyDelete
  5. Excellent read, Positive site, I have read a few of the articles on your website now, and I really like your style.
    Thanks a million and please keep up the effective work and also get to know about Angular Development Company

    ReplyDelete
  6. Thanks for Share the Details of AngularJS , AngularJS Training, AngularJS Courses, AngularJS Certifications Process and Understand the Clear Concept.

    AngularJS Training in Bangalore
    AngularJS Course in Bangalore
    AngularJS Online Training in Bangalore

    ReplyDelete
  7. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.
    Dedicated Angular JS Developers in India

    ReplyDelete
  8. Thanks you and excellent and good to see the best software training courses for freshers and experience candidates to upgade the next level in an Software Industries Technologies,
    AngularJS Training in Bangalore
    AngularJS Course in Bangalore
    Best AngularJS Training Institutes in Bangalore
    AngularJS Online Training in Bangalore

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. AngularJS Training in Bangalore | Thanks you and excellent and good to see the best software training courses for freshers and experience candidates | AngularJS Course in Bangalore |
    Best AngularJS Training Institutes in Bangalore | to upgrade the next level in an Software Industries Technologies | AngularJS Online Training in Bangalore

    ReplyDelete

  11. It is really very helpful for us and I have gathered some important information from this blog.
    Dedicated Angularjs Developers in India

    ReplyDelete
  12. Great Post. Very informative. Keep Sharing!!

    Angular Training in Noida

    Our students 3,47,689+, Our Consultants 146+, Our Courses 180+, Our Recruiters 884+
    For more details about the course fee, duration, classes, certification, and placement call our expert at 70-70-90-50-90

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. Very nice blog keep sharing such informative text. For expert tarining with guaranteed placement assistance Join Ducat for angular training in noida

    ReplyDelete
  15. AngularJS course in Noida
    https://aptronsolutions.home.blog/2022/08/02/whats-new-in-angular-14-heres-a-quick-look-at-the-features-updates/

    ReplyDelete