如何在 ng-repeat 中更新 ng-model

How to update ng-model inside ng-repeat

在这种情况下,如何从视图中更新 ng-model?

我在更新 ng-model 时遇到问题。抱歉,如果有错误或者我做错了什么!我是网络开发的新手!

我的 HTML 代码如下所示:

<div id="loadedCart" ng-show="ifLoadCart">
        <div ng-repeat="book in cartbooks" repeat-finish>
            <br>
            <!--<img src="book.path" alt="img of book"></img>-->
            <h6 ng-click="deleteBook(book.id)">{{book.name}}</h6>
            <h6>{{book.authors}}</h6>
            <h6>{{book.price}}</h6>
            <h6>{{book.qboy}}</h6>
            <input ng-model="thisoneshould" type="number" min="0" required>
            <input type="submit" ng-click="changeQuant(book.id)" value="Update quantity">
            <br><br><br>
        </div>
        <div><button ng-click="checkout()">Checkout</button></div>
    </div>

我在控制器中的代码如下所示:

    $scope.thisoneshould = 0;
    //other variables that are defined...

    $scope.changeQuant = function(x){
        $scope.updateCart(x);
    }
    $scope.updateCart = function(x){
        $scope.showLoginErrorMsg = false;
        $scope.needToLogin = false;
        $scope.showLoginErrorMsg = false;
        $scope.ifhomepage = false;
        $scope.ifSuccessful = false;
        $scope.ifbookpage = false;
        $scope.ifcheckpage = false;
        $scope.ifShowQuantity = false;
        $scope.additionSuccess = false;
        $scope.ifLoadCart = true;
        console.log(x);
        console.log($scope.thisoneshould);
        //$scope.cartbooks = [];
        if ($scope.thisoneshould!=0)
        {
            console.log($scope.thisoneshould);
            $http.put('updatecart',{'bookId': x, 'quantity': $scope.thisoneshould}).then(function(response){
                $scope.itemsInCart = response.data;
           });
        }
        else {
            $http.delete('deletefromcart/'+x).then(function(response){
                $scope.itemsInCart = response.data;
            });
        }
    }

谁能告诉我我的代码似乎有什么问题,为什么会出错,我该如何解决?

每当值发生变化时,您都需要通知控制器。更新控制器中值的某种事件。

Angularjs 无论如何都提供了双向数据绑定的功能。您的变量应该具有更新后的值。在下面的示例中,我使用 ng-changeng-model

演示

// Code goes here

var app =angular.module('testApp',[])
app.controller('testCtrl',function($scope){
   $scope.updated = 0;
   $scope.print = function(test){
     console.log(test);
   }
});
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
  </head>
  <body ng-app="testApp" ng-controller="testCtrl">
     <input ng-model="thisoneshould" ng-change="print(thisoneshould)" type="number" min="0" required>
  </body>
</html>