I would like to know if there is a known conflict between jQuery UI "autocompleteselect" event and some AngularJS event?
Here is my case : I have a table and an autocomplete input
<label for="addFruit">Add a fruit</label>
<input type="text" fruit-autocomplete ng-model="fruit"/>
<table>
<thead>
<tr>
<th>Label</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="fruit in fruits | orderBy:fruitsOrder">
<td>
{{fruit.label}}
</td>
<td>
<a title="Remove" href="javascript:void(0)" ng-click="rmFruit(fruit)">
Remove
</a>
</td>
</tr>
</tbody>
</table>
I have declared my autocomplete in a directive
app.directive('fruitAutocomplete', ['$http', function($http){
return function(scope, element, attrs){
element.autocomplete({
select : function(event, ui){
scope.fruit = ui.item; // Stores the selected fruit
scope.addFruit(); // Perform addFruit()
},
source: ... //Get my custom Json source
}).data('autocomplete') .... // Render in ul
};
}]);
And here is a part of the content of my controller
/*
* Methods
*/
// Add a fruit method
$scope.addFruit = function(){
this.fruits.push({'label' : 'test'}); // Add a new fruit to fruits
};
// Remove a fruit method
$scope.rmFruit = function(fruitToRemove){
var index = this.fruits.indexOf(fruitToRemove);
this.fruits.splice(index, 1);
};
$scope.fruit = null; // the selected fruit
$scope.fruits = fruitsList; // fruitList is the object containing all the fruits
$scope.fruitsOrder = 'label';
Everything works fine! Except when I select something in the autocomplete list.
Indeed, when I select an item, the select option is well fired and scope.addFruit() too (my $scope.fruits object is updated too!). But my table is not immediately updated!
So I tried to add a button "Add" which would fire the same method as my autocomplete select. Like this :
<button type="submit" ng-click="addFruit()">
Add
</button>
When clicked the scope.addFruit() is fired, and surprisingly, my table is immediately updated!
I searched and discovered that, when I select something in my autocomplete list, and then type something in my autocomplete field, my table is updated. So it seems that something is happening with an "on change" event somewhere.
Maybe some of you have experienced this situation or maybe I am just missing a point somewhere in my code. Maybe should I use $watch? or another method?
Thanks for you help :)
You should try wrapping your 'select' callback with $scope.$apply function.
...
select : function(event, ui){
scope.$apply(function(){
scope.fruit = ui.item; // Stores the selected fruit
scope.addFruit(); // Perform addFruit()
});
},
...
You can read more about $apply function in Scope Docs.