angularjs - Angular directives collaboration -


so here trying implement autocomplete suggestion angular , need expertise.

here html:

<div my-autosuggest>     <input type="text" my-autosuggest-input>     <ol>          <li ng-repeat"item in items" my-autosuggest-list>...</li>     </ol> </div> 

i don't want use templates generate <li> elements. (i want flexible use kind of element in order , maybe other elements in between list , dropdown)

the hard part respond arrow keys on input highlight next/prev element in list. how let other directive my-autosuggest-list know should select next element my-autosuggest-input directive.

note might have multiple autosuggests in 1 controller this:

<div ng-controller="mycontroller">    <div my-autosuggest>        <input type="text" my-autosuggest-input>        <ol>             <li ng-repeat"item in items" my-autosuggest-list>...</li>        </ol>    </div>    <div my-autosuggest>        <ol>             <li ng-repeat"item in items" my-autosuggest-list>...</li>        </ol>        <input type="text" my-autosuggest-input>    </div> </div> 

so far have tried $watch index change sometime watch wont called elements in list (maybe it's bug). $broadcast won't work because input might wrapped in controller or inside element broadcast won't heard list.

i tried put variable each autosuggest in root scope order in directives called in not parent child cannot initialize variable , create new 1 each time my-autosuggest called because my-autosuggest-input or others might called before that.

any suggestion on how design angular appreciated.

assuming my-autosuggest-input , my-autosuggest-list inside my-autosuggest. use series of $emitted , $broadcast events accomplish this.

inside my-autosuggest-input's link function add $emit when arrow key pressed:

element.on('keyup', function () {    // figure out if arrow key, if so:    $scope.$emit('listselect', { message: 'previtem' }); // or 'nextitem' }); 

inside my-autosuggest link function or controller add:

// add controllerid, listener doesn't handle own events. $scope.controllerid = math.random().tostring(); $scope.$on('listselect', function (e, data) {     if ($scope.controllerid !== data.controllerid) {         $scope.$broadcast('listselect', {              controllerid: $scope.controllerid,             message: data.message          });     } }); 

finally, inside my-autosuggest-list's link function or controller add:

$scope.$on('listselect', function (e, data) {     if (data.message === 'nextitem') {         // highlight next item.     } else {         // highlight previous item.     } }); 

in scenario my-autosuggest routes listselect events of children of children.


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -