Communication between commands in angularJS
The command section is the most difficult and important section. Next we will learn how to communicate between commands.
1. the effect we want to achieve is as follows:
Ii. source code example
Controller code example
/** Accordion foldable extended menu example * involves command nesting and communication between commands */myDirec. controller (SomeController2, function ($ scope) {$ scope. expanders = [{title: 'click me to expand ', text: 'Hi there folks, I am the content that was hidden but is now shown. '}, {title: 'click this', text: 'I am even better text than you have seen previously'}, {title: 'test', text: 'This is a test, hh ~ '}] ;}); // Defines the accordion command for coordinating the Controller myDirec. directive ('accordion', function () {return {restrict: 'ea ', replace: true, transclude: true, template :'
', Controller: function () {var expanders = []; // used to disable other expander this. gotOpened = function (selectedExpander) {angular. forEach (expanders, function (expander) {if (selectedExpander! = Expander) {expander. showMe = false ;}}) ;}; // used to register expander this. addExpander = function (expander) {expanders. push (expander) ;}}};}); // defines the expander command myDirec. directive ('pander2', function () {return {restrict: 'ea ', // It can only be placed on the element or attribute replace: true, // The format can be replaced by transclude: true, // allows you to move the original subnode of an identifier to the location of a new template. require: '^? Accordion ', // obtain the controller from the identifier of the same element. This controller is optional scope: {title:' = expanderTitle '}, template: ''+ '{title}' +'', link: function (scope, element, attrs, accordionController) {scope. showMe = false; accordionController. addExpander (scope); scope. toggle = function toggle () {scope. showMe =! Scope. showMe; accordionController. gotOpened (scope) ;}};}); Page code example
{Expander. text }}
3. analysis process
When the page is loaded, the expander is registered and then output is traversed through ng-repeat. The showMe attribute is false. When one of the pages is clicked, the toggle event is triggered, and the showMe attribute is changed to true, the text content is displayed. Of course, the ng-show command is used here. For details, refer to the usage of this attribute. Call the gotOpend method to disable other unselected expanders in turn.