javascript - Angular .then() 不起作用(发送 get 请求后不刷新 View )

标签 javascript angularjs

创建网上商店,当我管理用户购物车页面时,Angular 在调用 deleteFromCart() 后不会刷新 View ,因此我需要刷新页面。我缺少什么?正如我对 .then(f()) 所做的 promise ,但它不起作用 JS代码:

    var url = $location.absUrl() + "/products";

getProducts();
function getProducts() {
    $http.get(url).then(function (response) {
        $scope.total = 0;
        $scope.products = response.data;
        $scope.products.forEach(function (product) {
            $scope.total = $scope.total + product.price;
        })
    });
}

$scope.deleteFromCart = function (productId) {
    $http.get(url + '/' + productId).then(function () {
        getProducts();
    });
}

查看:

<div class="panel panel-primary" ng-controller="CartCtrl">
    <div class="panel-heading">
        <h3 class="panel-title">Your Cart</h3>
    </div>
    <div class="panel-body ">
        <table class="table table-bordered">
            <thead>
            <tr>
                <th>Product name</th>
                <th>Price</th>
                <th>Quantity</th>
                <th class="text-center">Action</th>
            </tr>
            </thead>
            <tr ng-repeat="product in products">
                <td>{{product.title}}</td>
                <td>{{product.price}}$</td>
                <td>3</td>
                <td class="text-center">
                    <a href="#" ng-click="deleteFromCart(product.id)" class="btn btn-danger btn-xs">Remove</a>
                </td>
            </tr>



        </table>
       <h4><span class="label label-primary pull-left">TOTAL : {{total}}$</span></h4>
        <button class="btn btn-success pull-right">Confirm Order</button>
    </div>

</div>

最佳答案

为什么要刷新页面,只需从列表中删除该产品

 <td class="text-center">
    <a href="#" ng-click="deleteFromCart(product.id,$index)" class="btn btn-danger btn-xs">Remove</a>
  </td>

$scope.deleteFromCart = function (productId,index) {
    $http.get(url + '/' + productId).then(function () {
         $scope.products.splice(index,1);
    });
}

关于javascript - Angular .then() 不起作用(发送 get 请求后不刷新 View ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41324523/

相关文章:

javascript - 推荐部分的 HTML 问题

javascript - 链接选择框

javascript - 你能使用Javascript获取图片上传时的exif数据吗?

javascript - JQuery 为文档就绪的嵌入字体提供了不正确的宽度

javascript - 如何使用for/in循环遍历js中的对象?

javascript - 无法使用 jQuery 数据表获取列值的总和(选中复选框)

javascript - 从父元素的子元素获取类值

javascript - 在 angularjs 中生成 javascript

javascript - Controller 如何知道范围有效

javascript - Angular - 使用两个按钮设置单个 bool 值(通过/失败)