AngularJS:为什么从对象中删除空模型字段?

Car*_*M74 7 javascript angularjs

在我的应用程序中,我有一个附加到表单的模型,类似于:

$scope.location = { description: "my descriptive description", address: "blah" }
Run Code Online (Sandbox Code Playgroud)

清除表单中的字段"description",绑定到ng-model ="location.description",从$ scope.location中删除字段,该字段变为:

$scope.location = { address: "blah" }
Run Code Online (Sandbox Code Playgroud)

现在我想保留"描述"字段.为了实现这种行为,我该怎么办?

谢谢你的帮助

小智 0

一种可能性是使用 ng-change 指令:

<input ng-model="desc" ng-change="setDescription()">
Run Code Online (Sandbox Code Playgroud)

在你的控制器中:

$scope.setDescription = function(){
    $scope.location.description = $scope.desc ? $scope.desc: "default" 
}
Run Code Online (Sandbox Code Playgroud)

以 Kozlowski 的评论为基础:http://jsfiddle.net/myMyQ/2/