AngularJS Reset only certain fields in a model

103 views Asked by At

I have an application with a form, the form fields are binded to a model, containing properties for each form field. Something like this:

var myFormFields = { 
   lastnamename: null,
   name: null,
   age: null,
   gender: null
};

I have many more in the application but this is just an example. Now what I want to do is create a resetfunction. What I created is a function that sets all desired properties back to null.

var resetForm = function() { this.age=null; this.gender=null;};

But I thought it would be nicer to have some kind of defaultform so that it could be copied over the original:

var defaultForm = {age: null, gender: null};
myFormFields = angular.copy(defaultForm);

The difficult thing in this, is that the above example throws away the properties I don't want to reset. I don't want all properties to be reset, only a select couple. Is there some handy way to achieve this without looping through the whole thing or without falling back to my first example?

1

There are 1 answers

1
chris On BEST ANSWER

You can use angular.extend. Assuming:

object1 = { a: null }
object2 = { a:123, b:456 }

then angular.extend(object2, object1) will result in:

object2 -> {a:null, b:456}