Update child component attributes

0

I'm making a very simple accordion component. A list of items where I click on one and it opens; if it already has some open, it closes and the other one opens.

<ns-accordion-item is-show="false">
  <accordion-head>
    <h3> Este títlulo pode conter o que quizer</h1>
  </accordion-head>
  <accordion-body>
      <form>[...]</form>
  </accordion-body>
</ns-accordion-item>

This is a very simple component, it does the transclude of <accordion-head> and <accordion-body> . The body has a ng-if of prop is-show (bind '='), so it only displays the content when needed.

I want to create another component, <ns-accordion> . The idea is for it to control and leave only a% open%.

So, it would look something like this:

<ns-accordion>
  <ns-accordion-item>[...]</ns-accordion-item>
  <ns-accordion-item>[...]</ns-accordion-item>
  <ns-accordion-item>[...]</ns-accordion-item>
</ns-accordion>

And now I do not know how to make magic happen.

I tried to make <ns-accordion-item> change attr <ns-accordion> of is-open there in $ postLink

ctrl.$postLink = function() {
  $currentAccordion = $element.find('ns-accordion-item[is-show="true"]');

  $element.on('click', 'ns-accordion-item', function(){
    var $el = angular.element(this);
    $currentAccordion.attr('is-show', false);
    $currentAccordion = $el.attr('is-show', true);
  });
};

Although it changes the attribute, the accordion-item ignores this change and does not fire $ onChange.

Does anyone know where I'm going wrong? Is this the right solution?

    
asked by anonymous 30.08.2017 / 19:40

1 answer

1

You can use $emit on $scope of your ns-accordion-item to notify ns-accordion when they are clicked, so ns-accordion uses $broadcast to notify ns-accordion-item that they should% / p>

$emit issues an event to the parent scopes from where it was issued.

$broadcast issues an event to the child scopes from where it was issued.

So you have your components talk to their proper scope trees. It may be a problem if you enter a set of ns-accordion and ns-accordion-item , but then you can do a workaround using ids for ns-accordion .

Doc $emit link

Doc $broadcast link

    
31.08.2017 / 14:16