AngularJs:使用 ng-model 时输入值也会发生变化。我也尝试过 ng-value 和 ng-bind
AngularJs: Input value changes in display too using ng-model. I have tried ng-value and ng-bind too
<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>
当我输入保存时,新数据完美地按行保存并显示,但是当我在输入中重新输入新值时。之前保存的值在我输入时发生变化。
您面临的问题是,当您调用 RecipeService.save($scope.shoppingItem);
时,RecipeService 将 reference 保存到您的范围变量。
因此,我可能会尝试这样做,而不是直接分配变量:
RecipeService.save(angular.copy($scope.shoppingItem));
这将创建 $scope.shoppingItem
引用的对象的新副本,并允许您编辑其中一个对象而不影响另一个。
<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>
当我输入保存时,新数据完美地按行保存并显示,但是当我在输入中重新输入新值时。之前保存的值在我输入时发生变化。
您面临的问题是,当您调用 RecipeService.save($scope.shoppingItem);
时,RecipeService 将 reference 保存到您的范围变量。
因此,我可能会尝试这样做,而不是直接分配变量:
RecipeService.save(angular.copy($scope.shoppingItem));
这将创建 $scope.shoppingItem
引用的对象的新副本,并允许您编辑其中一个对象而不影响另一个。