简体   繁体   中英

Pass variable to custom Angular directive

I have an accordion list, in which I want to be able to open certain items. I have created accordion-open directive, which should open the particular item if shouldBeOpen is true

Here is the HTML element (items are printed in loop)

<div class="m-list-item-head accordion-item" accordion-open="{{shouldBeOpen}}">

And here is my custom directive

(function () {
  'use strict';

  angular.module('myApp').directive('accordionOpen', function () {
    return {
      restrict: 'A',
      link: function(scope, element) {
          if (open) {
            $(element).closest('.accordion-item').siblings().slideDown('fast');
            $(element).closest('.accordion-item').addClass('opened');
          }
      }
    }
  });
})();

I am not able to read the contents of accordion-open within the directive.

The interpolate expressions are not required. So change to :

accordion-open="shouldBeOpen"

Next, add attrs to your link function:

link: function(scope, element, attrs)

And use $eval to get the value of the attribute in your link function:

console.log(scope.$eval(attrs.accordionOpen))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM