Reputation: 1901
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
Upvotes: 0
Views: 901
Reputation: 16660
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/
Upvotes: 2