我在html表单中使用了md-autocomplete,然后我想在提交后将其字段设置为空。我尝试使用$setPristine()
,如代码片段所示,但它无法正常工作。我还尝试将模型分配给null
或空字符串,但也没有成功。
PS:我使用的Angularjs版本是v1.3.15
angular.module("myApp", ["ngMaterial"])
.controller("main", function($scope){
$scope.searchString = "";
$scope.routeToSearchPage = function (searchString, form) {
$scope.form.$setPristine();
};
$scope.simulateQuery = false;
$scope.isDisabled = false;
$scope.states = loadAll();
$scope.querySearch = querySearch;
function querySearch (query) {
var results = query ? $scope.states.filter( createFilterFor(query) ) : $scope.states,
deferred;
if ($scope.simulateQuery) {
deferred = $q.defer();
$timeout(function () { deferred.resolve( results ); }, Math.random() * 1000, false);
return deferred.promise;
} else {
return results;
}
}
function loadAll() {
var allStates = "aaa, bbbb, cccc, bla";
return allStates.split(/, +/g).map( function (state) {
return {
value: state.toLowerCase(),
display: state
};
});
}
function createFilterFor(query) {
var lowercaseQuery = angular.lowercase(query);
return function filterFn(state) {
return (state.value.indexOf(lowercaseQuery) === 0);
};
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular-animate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular-aria.js"></script>
<script src="//rawgit.com/angular/bower-material/master/angular-material.js"></script>
<div ng-app="myApp">
<div ng-controller="main">
<form name="form"
ng-submit="submit(searchString);$event.preventDefault();">
<md-autocomplete
md-floating-label="search"
ng-disabled="isDisabled"
md-no-cache="noCache"
md-selected-item="selectedItem"
md-search-text="searchString"
md-items="item in querySearch(searchString)"
md-item-text="item.display"
ng-keyup="$event.keyCode == 13 ? routeToSearchPage(searchString) : null">
<md-item-template>
<span md-highlight-text="searchString" md-highlight-flags="^i">{{item.display}}</span>
</md-item-template>
</md-autocomplete>
</form>
<md-button ng-click="routeToSearchPage(searchString, form)">
<md-icon class="material-icons">search</md-icon>
</md-button>
</div>
</div>
答案 0 :(得分:0)
以下是清除md-autocomplete
- CodePen
您的代码段实际上并未显示应显示的md-autocomplete
。
JS
$scope.clear = function () {
$scope.searchString = null;
};
我还删除了下面的标记,以使CodePen正常工作:
ng-keyup="$event.keyCode == 13 ? routeToSearchPage(searchString) : null">