【问题标题】:AngularJs: Input value changes in display too using ng-model. I have tried ng-value and ng-bind tooAngularJs:使用 ng-model 也可以在显示中更改输入值。我也尝试过 ng-value 和 ng-bind
【发布时间】:2020-08-28 16:40:52
【问题描述】:
 <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>

当我输入保存时,新数据会完美地保存行并显示,但是当我在输入中重新输入新值时。之前保存的值会在我键入时发生变化。

【问题讨论】:

  • 能否请您发布代码示例?并告诉我们您预计会发生什么?
  • @TheLeb 是提供的兄弟
  • 确认一下,问题是item.itemName的值随着你输入而改变?
  • 是的,它会随着我输入而改变
  • 那么我认为问题在于您将输入绑定到页面上的控件而不是模型的属性。我是新手,但发现本教程非常有帮助。如果您有时间,请考虑关注:angular.io/tutorial

标签: angularjs angularjs-directive angular-ui-router angularjs-scope


【解决方案1】:

您面临的问题是,当您调用 RecipeService.save($scope.shoppingItem); 时,RecipeService 会将 reference 保存到您的范围变量。

所以,与其直接分配变量,我可能会尝试做这样的事情:

RecipeService.save(angular.copy($scope.shoppingItem));

这将创建$scope.shoppingItem 引用的对象的新副本,并允许您编辑其中一个对象而不影响另一个对象。

【讨论】:

    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 2014-06-29
    相关资源
    最近更新 更多