简体   繁体   中英

ng-model deletes element from object if the value is empty

I'm using the $resource service to access and update resource on my API.

However, I am having a problem when the value of the object bound to an ng-model is set to empty. The bound element gets deleted from the object. Thus, when saving my resource the element is not present on the passed data.

angular.module('myApp', [])

.controller('myCtrl', function($scope, $resource) {
   var Person = $resource('persons/:id.json', {id: @id});

   $scope.data = Person.get({id:123});
});

For example: data.name is set to '' in the template below:

<div ng-controller="myCtrl">
   <input type="text" ng-model="data.name" />

   <input type="button" ng-click="data.$save()" value="Save" />
</div>

I need the element present on the passed data when saving because it will determine if the API will set the actual value of the attribute to empty. Otherwise, the attribute doesn't get updated and it retains its old value.

In case anybody encounters the same issue, the problem was not with the ng-model but with the validation I added as part of the input

<input type="text" ng-model="data.name" ng-required="true" />

It's not part of the code shown in the question above but its related with the ng-required

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM