问题描述
<div class="form-group">
Name <input type="text" class="form-control" placeholder="item" ng-model="shoppingItem.itemName" required>
</div>
<div class="form-group">
Image URL <input type="url" class="form-control" placeholder="item" ng-model="shoppingItem.imgurl" required>
</div>
<div class="form-group">
<button type="button" class="btn btn-success" ng-click="save()" >Success</button>
</div>
app.controller('recipebookController',function($scope,$routeParams,RecipeService,$location){
$scope.shoppingItems =RecipeService.shoppingItems;
$scope.rp="Route parameter value"+RecipeService.shoppingItems[0].itemName;
$scope.save = function(){
RecipeService.save($scope.shoppingItem);
$location.path("/");
}
});
<div class="col-xs-12">
<ul class="list-group">
<li ng-repeat="item in shoppingItems"class="list-group-item text-center clearfix">
<span style="font-weight:bold">{{item.itemName}}</span>
<img ng-src="{{ item.imgurl }}" width="40" height="40"/>`
</li>
</ul>
</div>
当我输入save时,新数据将完美地按行保存并显示,但是当我将新值重新输入到输入中时。键入时,以前保存的值会发生更改。
解决方法
您面临的问题是,调用RecipeService.save($scope.shoppingItem);
时,RecipeService将引用保存到您的范围变量中。
因此,我可以尝试执行以下操作,而不是直接分配变量:
RecipeService.save(angular.copy($scope.shoppingItem));
这将创建$scope.shoppingItem
所引用对象的新副本,并使您可以编辑其中一个对象而不会影响另一个。