20

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;
    });
  })            
    }
  };
});

2 Answers 2

21

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I was overcomplicating the whole thing, and I've learned something from banging my head over this.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.