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
  • 21,049
  • 61
  • 166
  • 295

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,593
  • 13
  • 23
0

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

Make code simple and readable.

Maxim Shoustin
  • 78,004
  • 28
  • 199
  • 222
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
  • 29,589
  • 5
  • 38
  • 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
  • 64,963
  • 15
  • 144
  • 131
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,476
  • 4
  • 43
  • 66