我正在使用 $resource 服务访问和更新我的 API 上的资源。
但是,当绑定(bind)到 ng-model 的对象的值设置为空时,我遇到了问题。绑定(bind)元素从对象中删除。因此,在保存我的资源时,元素不存在于传递的数据中。
angular.module('myApp', [])
.controller('myCtrl', function($scope, $resource) {
var Person = $resource('persons/:id.json', {id: @id});
$scope.data = Person.get({id:123});
});
例如:data.name 在下面的模板中设置为'':
<div ng-controller="myCtrl">
<input type="text" ng-model="data.name" />
<input type="button" ng-click="data.$save()" value="Save" />
</div>
保存时我需要传递的数据中存在的元素,因为它将确定 API 是否会将属性的实际值设置为空。否则,该属性不会更新并保留其旧值。
最佳答案
万一有人遇到同样的问题,问题不在于 ng-model,而在于我作为输入的一部分添加的验证
<input type="text" ng-model="data.name" ng-required="true" />
它不是上面问题中显示的代码的一部分,但它与 ng-required 相关
关于javascript - 如果值为空,ng-model 从对象中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27942582/