angularjs - How to trigger an event in one view from a different view? -


i trying open angular accordian in header.html clicking button in body.html. triggering event in 1 view different view. have idea how in angular?

what can using events let accordion directive know happend or use shared service. considering performance, not make huge difference, if use $emit instead of $broadcast since event fired via $emit bubbles scope hierarchy , $broadcast sends event down. make sure fire event on $rootscope, won't event bubble anymore.

so in case want use events have method on component fires event via $emit on $rootscope follows:

function openaccordion() {     $rootscope.$emit('on-accordion-open', null); } 

you use in view, e.g. in body.html. remember function above part of directive / component or controller.

<button ng-click="vm.openaccordion()">open accordion</button> 

also note assume using controlleras syntax (set vm).

in accordion directive can hook listeners several events example on-accordion-open:

$rootscope.$on('on-accordion-open', function() {     // open accordion }); 

the other soltuion use shared service. in case create accordionservce aware of instances of accordions. service this:

angular.module('myapp').service('accordionservice', function() {    var accordions = {};     this.addaccordion = function(name, accordion) {        accordions[name] = accordion;    };     this.removeaccordion = function(name) {        delete accordions[name];    };     this.getaccordion = function(name) {        return accordions[name];    }; }); 

in accordion's controller add accordion accordionservice via

accordionservice.addaccordion('myaccordion', this); 

the this in snippet above refering accordion controller. thats important because if accordion in component in body.html, you'll controller instance , can call methods open.

so in body component can inject accordionservice , accordion call method:

accordionservice.getaccordion('myaccordion').open(); 

make sure define open on accordion's controller.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -