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?

2
  • Cant you just clear $scope.entry? Commented Nov 26, 2013 at 15:08
  • @smk no, it clears the entire form, I only want part of it cleared. Commented Nov 26, 2013 at 15:12

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

Comments

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 = {};
}

Comments

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 "".

Comments

0

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

Make code simple and readable.

1 Comment

So as I know there is no way.
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);
});

4 Comments

This gives the error: TypeError: Object #<Object> has no method 'push'
Fixed the error but this still does not work, it erases the entire form.
It should n't check the demo
Your demo does not reflect the question. It clears the entire set of data, I would like, for example in your demo, for last name to stay there when you click reset.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.