我正在尝试创建一个包装twitter typeahead插件的指令。我到目前为止是:
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: '='
- },$attrs) {
- $element.typeahead($scope.datasets);
- $element.bind('typeahead:selected',datum) {
- $scope.$apply(function() {
- $scope.ngModel = datum;
- });
- })
- }
- };
- });
您可以在指令内要求使用ngModel控制器。它将允许您访问链接功能中的模型控制器,请参见
http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController
在这里你可以找到一个例子,如何使用它的现实生活http://suhairhassan.com/2013/05/01/getting-started-with-angularjs-directive.html#.UhSdDOZdXUE