如何在角度预先搜索中使用ng-change

时间:2016-01-30 11:36:59

标签: javascript angularjs

我想在按键事件上搜索用户列表。我使用<input type="text" placeholder="Search people here..." ng-change="getMatchedUser();" ng-model="selected" data-typeahead="user as user.name for user in searchMembers | filter:$viewValue" typeahead-on-select="onSelect($item, $model, $label)" typeahead-template-url="customTemplate.html" /> <script type="text/ng-template" id="customTemplate.html"> <a style="cursor: pointer;"> <div class="search-div"> <span style="float: left;"><img ng-src="<?php echo base_url().UPLOAD_PROFILE ?>{{match.model.imageUrl}}" width="30" class="img-circle"></span> <div class="search-name"> <span>{{match.model.name}}</span><br/> <span ng-if="match.model.skillName.length"> <i class="skill">{{match.model.skillName}}</i> </span> </div> </div> <div style="padding-bottom:42px;" ng-if="match.model.length == 5"> <a href="<?php echo base_url(); ?>#/searchResult" style="float: left; padding: 18px 1px 5px 8px; color: black;"> Show More Results </a> </div> </a> </script> $scope.getMatchedUser = function(){ $scope.searchValue = $scope.selected; $http({ method : "POST", url : BASE_URL + 'getMatchedUser', data : $.param({"typeValue": $scope.selected}), headers : { 'Content-Type' : 'application/x-www-form-urlencoded'} }).success(function(data){ if(data.status == "success"){ $scope.searchMembers = data.searchMembers; } }); }; 来显示列表,但是第一次按键结果列表没有显示。

这是我的代码:

{{1}}

1 个答案:

答案 0 :(得分:7)

ng-change实际上是在ng-model更新之前触发的。

我找到的一个解决方案只是将typeahead-wait-ms属性(可忽略不计的时间范围)添加到您的预先输入input元素

<input type="text" 
       placeholder="Search people here..." 
       ng-change="getMatchedUser();"  
       ng-model="selected" 
       data-typeahead="user as user.name for user in searchMembers | filter:$viewValue" 
       typeahead-wait-ms=10
       typeahead-on-select="onSelect($item, $model, $label)" 
       typeahead-template-url="customTemplate.html"  />

这个10毫秒的暂停应足以让ng-model在触发ng-change事件之前更新。