reset button in angular js

Sara picture Sara · Mar 17, 2014 · Viewed 17.6k times · Source

I have a "clear" button, once user hit it all the data in container,all binding and the radio buttons should be reset (like initially). Currently only the view becomes empty but the container has still the old value. How can I fix it?

<div class="field">
         <textarea name="price" ng-model="list.price"></textarea>
</div>

 <input type="radio" ng-model="list.phone" value="1" />cell
 <input type="radio" ng-model="list.phone" value="2" />home

<button class="btn btn-primary btn-large center" type="reset"  ng-click="">
                        Clear
</button>

Answer

Tom picture Tom · Mar 17, 2014

Set ng-click to some function, say reset()

<button class="btn btn-primary btn-large center" 
        type="reset" 
        ng-click="reset()">Clear
</button>

and then set the model to an empty object

$scope.reset = function() {
    $scope.list = {};
}

Or, if $scope.list is prepopulated, you could do something like this (taken from angular docs):

function Controller($scope) {
    $scope.master = {};

    $scope.reset = function() {
      $scope.list = angular.copy($scope.master);
    };

    $scope.reset();
}