在文本输入模型集之后,角度搜索过滤器中断

时间:2015-03-20 19:35:22

标签: angularjs angularjs-directive

我正在编写一个组合框作为指令,并且遇到了一些麻烦。它的设置使得当有人点击输入时,它会在下拉列表中显示所有选项,并在您键入时过滤结果。如果单击结果,则应使用该值填充输入。

不幸的是,我似乎做错了什么,所以当你点击一个结果时,它会填充该字段,但如果你删除字段的值,而不是返回到原始搜索,它现在只有解析您选择的结果。它显示所有值,但只键入搜索与搜索文本和先前单击的值匹配的值。

如何调用该指令:

<combobox data="combobox.systems" results="systemSearch" placeholder="System"></combobox>

指令html:

<div class="combobox" ng-click="$event.stopPropagation()">
    <input type="text" ng-model="search.value" search-id="search.id" ng-class="{ resultsOpen: showDropdown }" ng-change="revealDropdown()" ng-focus="revealDropdown()" ng-blur="hideDropdown()">
    <a class="dropdown" ng-click="toggleDropdown($event)"></a>
    <div class="results" ng-show="showDropdown">
        <a ng-repeat="set in data | filter: { value: search.value }" ng-mousedown="setBox($event, set)" ng-bind-html="set.value | trustHTML"></a>
    </div>
</div>

指令代码:

directive('combobox', ['$filter', function ($filter) {
    return {
        restrict: 'E',
        templateUrl: 'combobox.html',
        scope: {
            'data': '=data',
            'search': '=results'
        },
        link: function (scope, element, attrs) {
            scope.search = { id: '', value: '' };
            if (typeof attrs.placeholder != 'undefined') 
                element.find('input').attr('placeholder', attrs.placeholder);
            scope.showDropdown = false;
            if (typeof scope.data == 'undefined') 
                scope.data = [];

            scope.toggleDropdown = function ($event) {
                $event.stopPropagation();
                scope.showDropdown = scope.showDropdown?false:true;
            };
            scope.revealDropdown = function () {
                if ((isNaN(scope.search) || scope.search.length == 0) && $filter('filter')(scope.data, scope.search).length) 
                    scope.showDropdown = true;
                else 
                    scope.showDropdown = false;
            };
            scope.hideDropdown = function () {
                scope.showDropdown = false;
            };
            $('html').click(function () {
                scope.hideDropdown();
                scope.$apply();
            });

            scope.setBox = function ($event, set) {
                scope.search = set;
            }
        }
    }
}])

我确实知道将setBox方法更改为

scope.setBox = function ($event, set) {
    scope.search = angular.copy(set);
}

这有点帮助,但几乎没有解决问题。我已经让一个Plunker尝试提供帮助:http://plnkr.co/edit/wYfveGDYaVUpzcOWDbSz

我做错了什么?

1 个答案:

答案 0 :(得分:0)

这应该有效:

scope.setBox = function ($event, set) {
    scope.search.value = set.value;
};

如果您需要记录所选项目:

scope.setBox = function ($event, set) {
    scope.search.value = set.value;
    scope.selected = angular.copy(set);
};

另外,你真的不需要传递$ event并设置到你的setBox方法中,你可以这样做:

scope.setBox = function () {
    scope.search.value = this.set.value;
    scope.selected = angular.copy(this.set);
};