繁体   English   中英

角材料自动完成-选择时搜索

[英]Angular Material Autocomplete - Searches on Select

我在Angular Material中创建了这个很酷的小控件,欢迎任何人使用(请参见小提琴)。 它基本上是Angular Material的“自动完成”字段,在您键入时会利用Google的Geolocation服务。 由于没有延迟指令,因此我添加了特殊代码,仅在用户在700毫秒后停止键入时才进行搜索。

我的问题是-为什么选择项目后MD自动完成功能会触发查询事件?

这是HTML:

<md-autocomplete flex style="width: 50%; margin: auto; padding-top: 10em" 
    md-no-cache="false"
    md-selected-item="ctrl.orig_loc"
    md-search-text="ctrl.orig_loc_query"
    md-items="item in querySearch(ctrl.orig_loc_query)"
    md-selected-item-change="selectedItem(ctrl.orig_loc)"
    md-item-text="ctrl.orig_loc.formatted_address"
    md-floating-label="Type address or location name">

    <span md-highlight-text="">{{item.formatted_address}}</span>
</md-autocomplete>

这是JS querySearch函数:

// this is called every time a user types a character AND when item is selected... for some odd reason
$scope.querySearch = function(query) {
    var deferred = $.Deferred();

    // clear old request if something typed within 700ms
    if (locQuery) {
        clearTimeout(locQuery);
    }
    // run the query in 700ms. it will be cleared if the user types within 700ms
    locQuery = setTimeout(function() {
        // call google's geocoder
        geocoder.geocode({
            'address': query
        }, deferred.resolve);
    }, 700);

    return deferred.promise().then(function(response) {
        return response;
    });
};

这是小提琴: https : //jsfiddle.net/NeoSHNIK/jgpgv4Ls/3/

同样,问题是-选择之后,它将进行另一次搜索...为什么?

我有点想通了。 之所以发生这种情况,是因为该字段的变量“ searchText”在被格式化程序“ {{item.formatted_address}}”格式化之前已更改了两次。 角材料库中的$ scope。$ watch正在监视此字段。 因此,每次更改时,他们都会调用handleSearchText()进行搜索。 因此,他们应该真正添加一个“延迟”概念来解决我的问题以及解决远程搜索的问题(不想搜索用户键入的每个字符)。 向自动完成控件添加延迟会很好。 但是现在我只是修改了角材料库,它完成了工作:

  function configureWatchers () {
    var wait = 700; //MY HACK
    $attrs.$observe('disabled', function (value) { ctrl.isDisabled = $mdUtil.parseAttributeBoolean(value, false); });
    $attrs.$observe('required', function (value) { ctrl.isRequired = $mdUtil.parseAttributeBoolean(value, false); });
    $attrs.$observe('readonly', function (value) { ctrl.isReadonly = $mdUtil.parseAttributeBoolean(value, false); });
    $scope.$watch('searchText', wait ? $mdUtil.debounce(handleSearchText, wait) : handleSearchText);
    $scope.$watch('selectedItem', selectedItemChange);
    angular.element($window).on('resize', positionDropdown);
    $scope.$on('$destroy', cleanup);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM