NJeffries
NJeffries

Reputation: 105

How do I clear the search field with angular?

I've added a clear button in my HTML but I'm still a newbie. How would I make my clear button empty the search field on click? If a user enters some text and nothing comes up, I'd like to be able to wipe it out.

Fiddle: https://jsfiddle.net/kiddigit/znasgeez/1/

  <button class="btn btn-success pull-right">
    <span ng-model="search" ng-click="clearSearch()"></span> Clear
  </button>


var artistControllers = angular.module('artistControllers', []);

artistControllers.controller('ListController', ['$scope', '$http', function($scope, $http) {
  $http.get('js/data.json').success(function(data) {
    $scope.artists = data;
    $scope.artistOrder = 'name';
  });
}]);

artistControllers.controller('DetailsController', ['$scope', '$http','$routeParams', function($scope, $http, $routeParams) {
  $http.get('js/data.json').success(function(data) {
    $scope.artists = data;
    $scope.whichItem = $routeParams.itemId;

    if ($routeParams.itemId > 0) {
      $scope.prevItem = Number($routeParams.itemId)-1;
    } else {
      $scope.prevItem = $scope.artists.length-1;
    }

    if ($routeParams.itemId < $scope.artists.length-1) {
      $scope.nextItem = Number($routeParams.itemId)+1;
    } else {
      $scope.nextItem = 0;
    }

  });
}]);

Upvotes: 2

Views: 4720

Answers (2)

Trevor Ward
Trevor Ward

Reputation: 612

You can just set the scope variable that your input is bound to to an empty string.

http://jsfiddle.net/Lvc0u55v/5156/

basically, in your clearSearch() method you do

$scope.query = "";

Upvotes: 3

jsmtslch
jsmtslch

Reputation: 718

Try using angular.copy({}). Which will empty your fields.
Have a look at the plunker I created:https://plnkr.co/edit/LYZeKt3jZXhoCmfvgmLw?p=preview

$scope.search = angular.copy($scope.default);

is the key here.

Upvotes: 2

Related Questions