我正在尝试创建一个包装 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: '='
},
link: function ($scope, $element, $attrs) {
$element.typeahead($scope.datasets);
$element.bind('typeahead:selected', function(obj, datum) {
$scope.$apply(function() {
$scope.ngModel = datum;
});
})
}
};
});