1

When the user clicks on a radio button I run:

$scope.clientClick = function() {

    //do stuff
}

I have a form, and I would like half of the fields on the form to be cleared in the above method.

I have done:

 $scope.clientClick = function() {

    $scope.entry.first_name = '';
    $scope.entry.last_name = '';
    $scope.entry.email = '';
    $scope.entry.tel = '';
    $scope.entry.gender = '';
    $scope.entry.job = '';
    $scope.entry.age = '';
}

But is there an easier way rather than listing each field again?

panthro
  • 22,779
  • 66
  • 183
  • 324

5 Answers5

0
function initObject(obj) {
  for (var i in obj) {
    if (obj.hasOwnProperty(i)) {
      switch(typeof obj[i]){
        case 'string':
          obj[i] = '';
          break;
        case 'number':
          obj[i] = 0;
          break;
      }
    }
  }
}

Use this function. NEVER do this $scope.entry = {} or $scope.entry.name = null, it's safer and you won't get unnecessary errors when you have some parts of your code that expect a type. It's a lot easier just to set a string to "".

Mário
  • 1,603
  • 14
  • 24
0

I would use $scope.entry = null or $scope.entry = {}.

Make code simple and readable.

Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
0

Short answer

['first_name', 'last_name', ...].forEach(function (f) {
    $scope.entry[f] = '';
});

Long answer

In JavaScript, properties can be accessed in two ways:

obj.prop
obj['prop']

You can keep a list of strings with the properties that you want to clear, and then just iterate over it clearing each in turn.

Roberto Bonvallet
  • 31,943
  • 5
  • 40
  • 57
0

I'd suggest that if you have a dependency to the radio button then the view model should reflect that it could be cleared:

$scope.entry.dependant = { first_name: '' ... }

$scope.clientClick = function() {

    $scope.entry.dependant = {};
}
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
0

I would have done some thing like Reset a model with angular.js:

$scope.initial = [
  {
    first_name : '',
    last_name : '',
    email : '',
    tel : '',
    gender : '',
    job : '',
    age : ''
  }            
];

Demo

$scope.clientClick = function() {
  angular.copy($scope.initial, $scope.entry);
});
Community
  • 1
  • 1
ssilas777
  • 9,672
  • 4
  • 45
  • 68