Wrapping angular-ui-typeahead breaks the on-select callback

675 Views Asked by At

I'm trying to wrap AngularUI's typeahead directive with my own directive so I can package up some shared data/behavior for easier reuse in my app: Plunker

In the onSelect callback, why does the correct value only show up after the timeout?

For reference, this works correctly without the wrapping directive: Plunker

2

There are 2 best solutions below

1
On

Use = inside an isolate scope directive so that the bound function is called only after the model is updated:

scope : {
    selectedModel : "=",
    onSelect : "="
}

Plunker

0
On

You have to use an ampersand in the directive and pass the item in the html. From the Angular Docs "The & binding allows a directive to trigger evaluation of an expression in the context of the original scope, at a specific time. Any legal expression is allowed, including an expression which contains a function call. Because of this, & bindings are ideal for binding callback functions to directive behaviors."

Isolated scope in directive:

scope: { 
onSelect: '&'
}

Html

<input autocomplete="off"
placeholder="Enter &ldquo;jo&rdquo; and pick something"
ng-model="selectedModel"
typeahead="v as v.name for v in vendors | filter:$viewValue"
typeahead-on-select="onSelect({item: $item})" />

Callback function should take an item

function myCallback(item) {
console.log(item);
}