使用Bootstrap typeahead与Angular

20

我目前正在开发一个使用Twitter Bootstrap和AngularJS良好结合的Web应用程序。然而,在使用typeahead作为ng-model时遇到了问题。

在输入时一切正常,但是当我选择一个项目(建议)时,除非我在选择值后更改文本框的值,否则该值不会反映在Angular控制器中。 输入->选择->输入可以工作,输入->选择无法工作。

HTML:

<form ng-submit="addAssignment(assignName)">
  <div class="input-append">
    <input type="text" placeholder="Type a name" ng-model="assignName" ng-change="dostuff()" data-provide="typeahead" data-source="{{ teamNames }}">
    <button class="btn" type="submit">Add</button>
 </div>
</form>

Angular 代码:

 $scope.addAssignment = function(name) {
    alert(name);
    return;
 }

我已添加ng-change函数,仅用于检查模型值何时更改。 当手动输入时才会更改它,而不是在从typeahead中选择的列表中出现的值更改时。

感谢任何有助于解决此问题的回复。谢谢!


这个问题已经解决了吗? - Abdul Azeez
7个回答

22
我建议查看AngularUI / boostrap存储库中的typeahead指令:http://angular-ui.github.com/bootstrap/ 它是纯AngularJS本地实现,因此不需要任何第三方依赖项。除此之外,它与AngularJS生态系统非常好地集成在一起,因为它: *使用从“select”指令中知道的简洁语法 *理解AngularJS承诺,因此可以使用最少的努力动态获取结果,使用 $http

你可能会使用angular-strap,因为它支持最新版本的angularjs ;) - genuinefafa

21

1
链接是否已经移动到其他地方了? - Harish Kayarohanam

9

我使用angular(以及bootstrap css用于样式)制作了这个本地typeahead实现,可能会对寻找如何实现此功能的人有所帮助。

演示请看:https://jsfiddle.net/bh29tesc/

Angular指令:

angular.module('app').
directive('typeahead', ['$compile', '$timeout', function($compile, $timeout)   {
    return {
        restrict: 'A',
        transclude: true,
        scope: {
            ngModel: '=',
            typeahead: '=',
            typeaheadCallback: "="
        },
        link: function(scope, elem, attrs) {
            var template = '<div class="dropdown"><ul class="dropdown-menu" style="display:block;" ng-hide="!ngModel.length || !filitered.length || selected"><li ng-repeat="item in filitered = (typeahead | filter:{name:ngModel} | limitTo:5) track by $index" ng-click="click(item)" style="cursor:pointer" ng-class="{active:$index==active}" ng-mouseenter="mouseenter($index)"><a>{{item.name}}</a></li></ul></div>'

            elem.bind('blur', function() {
                $timeout(function() {
                    scope.selected = true
                }, 100)
            })

            elem.bind("keydown", function($event) {
                if($event.keyCode == 38 && scope.active > 0) { // arrow up
                    scope.active--
                    scope.$digest()
                } else if($event.keyCode == 40 && scope.active < scope.filitered.length - 1) { // arrow down
                    scope.active++
                    scope.$digest()
                } else if($event.keyCode == 13) { // enter
                    scope.$apply(function() {
                        scope.click(scope.filitered[scope.active])
                    })
                }
            })

            scope.click = function(item) {
                scope.ngModel = item.name
                scope.selected = item
                if(scope.typeaheadCallback) {
                    scope.typeaheadCallback(item)
                }
                elem[0].blur()
            }

            scope.mouseenter = function($index) {
                scope.active = $index
            }

            scope.$watch('ngModel', function(input) {
                if(scope.selected && scope.selected.name == input) {
                    return
                }

                scope.active = 0
                scope.selected = false

                // if we have an exact match and there is only one item in the list, automatically select it
                if(input && scope.filitered.length == 1 && scope.filitered[0].name.toLowerCase() == input.toLowerCase()) {
                    scope.click(scope.filitered[0])
                }
            })

            elem.after($compile(template)(scope))
        }
    }
}]);

使用方法:

<input class="form-control" type="text" autocomplete="false" ng-model="input" placeholder="Start typing a country" typeahead="countries" typeahead-callback="callback" />

在编程中,"on the fiddle" 意味着某个功能或代码出现了问题。当你选择其中一个时,它不会被分配给 ngmodel。 - gdubs
它将item.name分配给ngModel。如果您需要整个对象,请使用回调函数。或者只需修改它以分配所需内容。 - ropsnou

3

我创建了一个折中的方法。基于这个示例: https://groups.google.com/forum/#!topic/angular/FqIqrs-IR0w/discussion ,我为typeahead控件创建了一个新模块:

angular.module('storageApp', []).directive('typeahead', function () {
return {
    restrict:'E',
    replace:true,
    scope:{
        model:'=',
        source:'&'
    },
    template:'<input type="text" ng-model="model"/>',
    link:function (scope, element, attrs) {
        console.log(scope.source);
        $(element).typeahead({
            source:scope.source,
            updater:function (item) {
                scope.$apply(read(item));
                return item;
            }
        });

        function read(value) {
            scope.model = value;
        }
    } // end link function
}; // end return
}); // end angular function

我在数据绑定方面遇到了一些问题,自动填充选项是从一个Angular控件中收集的,但我遇到了一个问题,即控件在此信息准备好之前就被创建了。因此,我向typeahead控件添加了一个html属性(datasource),并在构造函数中设置了一个$observe函数。

<typeahead id="addSupplier" model="addSupplier" placeholder="Skriv inn leverandør" class="typeahead" source="getSuppliers()" ></typeahead>

我认为这是一个不太优秀的解决方案,所以如果任何人有更好的想法,欢迎分享 :). 这个 bug 的详细描述在这里:https://github.com/angular/angular.js/issues/1284


你不需要使用 $(element).whatever,直接使用 element.whatever 即可。 - Andrew Rhyne

0

这是我使用过的另一种方法。它也很“脏”。这段代码可以直接放入您的控制器中。

$('#id_of_your_typeahead_input').change(function(event){
  $scope.$apply(function(scope){
    scope.your_ng_model = event.target.value;
  });
  $scope.your_ng_click_function();
});

虽然有点不干净,但这听起来最好。 - Hengjie

0

另一种选择

在HTML中

    <form ng-submit="submitRegion()">
        <input type="text" ng-model="currentRegion" id="region-typeahead" data-source="{{ defaultRegions }}"  data-provide="typeahead"/>
        <button type="submit" class="btn">Add</button>
    </form>

在你的控制器中

    $scope.defaultRegions = ["Afghanistan", "Australia", "Bahrain", "New Zealand" ];

    $scope.submitRegion = function(){
        $scope.currentRegion = $('#region-typeahead').val();
        $scope.addRegion(); //your add or click function you defined
        $scope.currentRegion = ''; //clear
    }

0

这是基于 @zgohr 的实现

$('#your-input-id-here').change((event)->
  angular.element("#your-input-id-here").scope().$apply((scope)->
    scope.your_ng_model = event.target.value
  )
)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接