Skip to content

Instantly share code, notes, and snippets.

@robrothedev
Last active December 10, 2015 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robrothedev/46e1b2a2470b1f8687ad to your computer and use it in GitHub Desktop.
Save robrothedev/46e1b2a2470b1f8687ad to your computer and use it in GitHub Desktop.
ngAutocomplete - Using a function in the controller when a location has been selected from the list
Working example: http://jsfiddle.net/n3ztwucL/
// ngAutocomplete Directive - https://github.com/wpalahnuk/ngAutocomplete
angular
.module('app', ['ngAutocomplete'])
.controller('LocationCtrl', LocationCtrl);
function LocationCtrl($scope) {
var vm = this;
vm.location = '';
vm.location_list = [];
vm.location_result = null; // this is the model we need to use
// autocomplete options
vm.autocomplete_options = {
types: 'establishment'
};
// look for a change in the location and do something
// its a little confusing because we're not watching the ng-model from this controller
// but rather the model that gets set from the ngAutocomplete directive
$scope.$watch(function() {
return vm.location_result;
}, function(location) {
if (location) {
vm.location_list.push(location);
vm.location = '';
}
});
}
<div ng-app="app" ng-controller="LocationCtrl as ctrl">
<input type="text"
ng-autocomplete
options="calendar_ctrl.autocomplete_options"
ng-model="ctrl.location"
details="ctrl.location_result">
<hr>
<button ng-if="ctrl.location_list.length" ng-click="ctrl.location_list = []">&times;</button>
<h4>Locations </h4>
<ul>
<li ng-repeat="location in ctrl.location_list track by $index">{{location.name}}</li>
</ul>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment