Reputation: 1619
I am trying to create a directive that wraps the twitter typeahead plugin. What I have so far is:
HTML:
<input ng-twitter-typeahead type="text" ng-model="participant" data="exampleData" />
{{ participant }}
I want the value for 'participant' to be updated when I select something on the typeahead. The typeahead itself works properly, but I can't capture the selected value. Below is the javascript:
var app = angular.module('myApp', [])
app.directive('ngTwitterTypeahead', function () {
return {
restrict: 'EA',
scope: {
data: '='
},
link: function ($scope, $element, $attrs) {
$element.typeahead($scope.data);
$element.bind('typeahead:selected', function(obj, datum) {
// I really don't know how to do this part
// the variable 'datum' is what I want to be passed to ng-model
// I tried things like:
// Including the ngModelController and typing:
// ngModel.$setViewValue(datum)
// but that didn't work.
}
};
});
I'm obviously missing something fundamental when it comes to AngularJS. Any help would be greatly appreciated!
EDIT **
I found the solution. I am clueless sometimes:
angular.module('siyfion.ngTypeahead', [])
.directive('ngTypeahead', function () {
return {
restrict: 'C',
scope: {
datasets: '=',
ngModel: '='
},
link: function ($scope, $element, $attrs) {
$element.typeahead($scope.datasets);
$element.bind('typeahead:selected', function(obj, datum) {
$scope.$apply(function() {
$scope.ngModel = datum;
});
})
}
};
});
Upvotes: 20
Views: 33368
Reputation: 14046
The twitter Typeahead project seems to be abandoned.
But you can use the Typeahead Angular directive from the Angular UI Bootstrap library that is being actively maintained as of now.
Upvotes: 0
Reputation: 6710
You could require ngModel
controller inside the directive. It will give you an access to the model controller inside the link
function, see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
Here you can find an example how to use it the real life http://suhairhassan.com/2013/05/01/getting-started-with-angularjs-directive.html#.UhSdDOZdXUE
Upvotes: 21