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

时间:2018-04-29 16:11:46

标签: angularjs angularjs-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;
            });
        }
    }

有人能告诉我我的代码有什么问题,为什么错了,我该怎么解决?

1 个答案:

答案 0 :(得分:-1)

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

Angularjs无论如何都提供双向数据绑定的功能。您的变量应具有更新的值。在下面的示例中,我使用 ng-change ng-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>