2014-02-11 32 views
44

如何使用angularJS清除單擊按鈕上的文本輸入?使用AngularJS單擊清除文本輸入

Search input

的X是一個單獨的鏈接,關於這一點我想觸發功能。

HTML

<input type="text" class="form-control" data-ng-model="searchAll"> 
<a class="clear" data-ng-click="clearSearch()">X</a> 
+2

添加你的HTML輸入的請。 –

回答

79

就明確範圍模型上點擊事件值,它應該爲你做的伎倆。

<input type="text" ng-model="searchAll" /> 
<a class="clear" ng-click="searchAll = null"> 
    <span class="glyphicon glyphicon-remove"></span> 
</a> 

或者,如果你保持你的控制器的$scope功能,並從那裏清除它。確保你已經正確設置你的控制器。

$scope.clearSearch = function() { 
    $scope.searchAll = null; 
} 
+0

謝謝,這個工程,但只有當代碼是內聯的,而不是在一個單獨的JS文件。你能告訴我你如何使它在一個單獨的JS文件中工作? – Barney

+2

看我的編輯。但是,爲什麼你想添加不需要它的附加代碼呢? –

15
$scope.clearSearch = function() { 
    $scope.searchAll = ""; 
}; 

http://jsfiddle.net/nzPJD/

的你如何能做到這一點的jsfiddle不使用內聯JS。

6

如果你想清理整個表格,你可以使用這種方法。 這是你的模型到控制器:

$scope.registrationForm = { 
    'firstName'  : '', 
    'lastName'  : '' 
}; 

你的HTML:

<form class="form-horizontal" name="registrForm" role="form"> 
    <input type="text" class="form-control" 
         name="firstName" 
         id="firstName" 
         ng-model="registrationForm.firstName" 
         placeholder="First name" 
         required> First name 
    <input type="text" class="form-control" 
         name="lastName" 
         id="lastName" 
         ng-model="registrationForm.lastName" 
         placeholder="Last name" 
         required> Last name 
</form> 

然後,你應該克隆/由保存清晰狀態:

$scope.originForm = angular.copy($scope.registrationForm); 

你的復位功能將是:

$scope.resetForm = function(){ 
    $scope.registrationForm = angular.copy($scope.originForm); // Assign clear state to modified form 
    $scope.registrForm.$setPristine(); // this line will update status of your form, but will not clean your data, where `registrForm` - name of form. 
}; 

以這樣的方式,你可以清理整個表單

+0

我確實實施了你的解決方案,對我來說,我確實發現了一個警告:TypeError:無法在Scope中讀取屬性'$ setPristine'undefined $ scope.resetForm我可以修復這個警告嗎? –

10

一個更容易和更短的方法是:

<input type="text" class="form-control" data-ng-model="searchAll"> 
<a class="clear" data-ng-click="searchAll = '' ">X</a> 

這一直爲我工作。

+0

你能解釋一下嗎?所以當我們點擊「X」時,我可以對它投票 –

+0

,那麼「searchAll」的模型值將變成空的,因爲當我們點擊「X」時我們已經爲該模型分配了空字符串。 !! data-ng-click =「searchAll =''」!!好的是,我們不必爲一行代碼製作和調用單獨的函數。 –

1

Robert's答案的啓發,但是當我們使用,

在過濾ng-click="searchAll = null",這使得該模型值null和在打開搜索不其正常功能工作,所以這將是更好足夠使用ng-click="searchAll = ''"代替

+0

你可以談談使用這種方法時的XSS含義嗎? – Justin

4
清除/重置單擊文本字段

最簡單的方法是清除/復位範圍

<input type="text" class="form-control" ng-model="searchAll" ng-click="clearfunction(this)"/> 

在控制器

$scope.clearfunction=function(event){ 
    event.searchAll=null; 
} 
0

在控制器

$scope.clearSearch = function() { 
    $scope.searchAll = ''; 
} 
0

試試這個,

this.searchAll = element(by.xpath('path here')); 
this.searchAll.sendKeys('');