2013-08-21 119 views
20

我正在尝试创建一个包装twitter typeahead插件的指令。我至今是:创建angular-js指令,更新ng-model

HTML:

<input ng-twitter-typeahead type="text" ng-model="participant" data="exampleData" /> 
{{ participant }} 

我想,当我选择的预输入的东西被更新为“参与者”的值。打字头本身工作正常,但我无法捕获选定的值。下面是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. 
    } 
    }; 
}); 

我明显失去了AngularJS的基本内容。任何帮助将不胜感激!

编辑**

我找到了解决办法。我有时很无能:

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

回答

21

您可能需要ngModel控制器里面的指令。它会给你的link函数内部模型控制器的访问,请参阅http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

在这里你可以找到一个例子如何使用它的现实生活http://suhairhassan.com/2013/05/01/getting-started-with-angularjs-directive.html#.UhSdDOZdXUE

+0

谢谢!我把整件事情搞得一团糟,而且我从这个问题上学到了一些东西。 – user2205763