0

I have an AngularJS model like this:

$scope.model = {name: "Joe", isMale: true};

In the view I bind the model.isMale to a checkbox.

Now I ask a backend for an update ($http.get()). In the onSuccess callback I simply assign the response value to $scope.model. If the backend does not send me the whole model, e.g. does not send the isMale flag, the $scope.model does not have the flag isMale any more. When I later on change the name for example in the UI and send these data to the backend, the flag isMale is not sent to the backend anymore, since the model does not contain it. Is there a way to check if the view elements' model-bindings do exist? Is there a better solution than just overwriting the model with the value I get from the backend?

Thanks

1 Answer 1

2

You can extend your model and overwrite your default model value with the one from api response. That way your default will be overridden only if that is present in api response:

angular.extend($scope.model, response)

for shallow copy, or

angular.merge($scope.model, response)

for deep(recursive) copy

This should work in your scenario

And do refer for the intricate details of difference between angular.copy(), 'angular.extend()' and angular.merge() here: http://davidcai.github.io/blog/posts/copy-vs-extend-vs-merge/

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

2 Comments

and use angular.merge if you want deep copy.
user angular.merge

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.