axel-zarate / js-custom-select

Custom auto-complete select box for AngularJS and Bootstrap
MIT License
68 stars 59 forks source link

Local filtering with Ajax-fetched data #21

Closed Amenel closed 8 years ago

Amenel commented 8 years ago

We are facing a problem in the use of this UI directive.

Suppose we are in the 'complex objects' scenario. We have: <div custom-select="s.id as s.name for s in states | filter: { name: $searchTerm }" ng-model="state"> </div>

This works flawlessly when states is a scope variable defined as a hand-coded array. However, from the moment we switch to a $resource data fetching, even of a locally stored json, the combobox no longer initializes by showing the value designated in ng-model. Viewing the value requires clicking the control (either the "Select..." text or the dropdown arrow) before the list items show at the same that the ng-model value does.

Is there a way of having this directive refresh its view, like ui-grids do when the data field is assigned a new value? Thx.

axel-zarate commented 8 years ago

The problem in this kind of scenarios is that it is hard to determine when the directive should refresh the item list; in case the item source is an async function that calls some server side resource, you wouldn't want to $watch for the function value on every digest cycle.

However, if you assign the item list to the result of a call to $resource or $http and then you assign the ng-model variable after that, it should detect the model change and reevaluate the item source variable.

I have not tested this case in particular but I think it should work. Please let me know if after doing these steps in this order the problem is resolved or not.

Amenel commented 8 years ago

We were actually embedding a custom-select in another directive that enriches it with action buttons (these allow editing and deleting the currently shown item). This means that the assigning of ng-model is automatic.

The data source (i.e. the list of items) is hence provided by a function Fn whose name is given in an attr of our directive. The controller of the directive then builds the "x as y for z in t" string expected by custom-select. The value of 't' is of course a function in the controller. I think my mistake was that 't' was returning Fn instead of its promise.

Anyway, the problem is resolved.

I believe that my initial intent, which is client-side filtering of Ajax-fetched data cannot actually be done, at least in a simple way. I've discovered that even though the data returned by the server is a valid JSON array, filter was spitting a 'notarray' error message like this one: Expected array but received: {"$$state":{"status":0}}

I seem to have noticed that even resolved promises are not pure Arrays but rather Objects.

If anybody needs clarification in the future, feel free to get in touch with me.

@axel-zarate: thanks a ton!