AngularJS $范围变量仅通过HTTP GET

时间:2015-12-03 15:17:14

标签: javascript angularjs http

我有一个API,我正在尝试从单独的AngularJS应用程序中获取数据。

我正在使用一个按钮来加载来自API的数据。按下时,它会调用$scope.getApiData函数,该函数绑定到名为$scope.productlist的变量。每个条目都有一个删除按钮,可以调用$scope.deleteProduct函数。

enter image description here

API工作正常,但它使用的是ASP.NET 5.

按下“更新”时调用的代码也会在“删除”按下后调用。

(function () {
'use strict';

angular
    .module('app')
    .controller('Products', main);

main.$inject = ['$scope', '$http'];

function main($scope, $http) {
    $scope.productlist = [];

    // Get products from API
    $scope.getApiData = function () {
        $http({
            method: 'GET',
            url: "http://localhost:65040/api/products",
        }).then(function successCallback(response) {
            $scope.productlist = response.data;
        }, function errorCallback(response) {
            alert('Error');
        });
    };

    // Delete a product
    $scope.deleteProduct = function (idx) {
        $http({
            method: 'DELETE',
            url: "http://localhost:65040/api/products",
            params: { 'id': idx },
        }).then(function successCallback(response) {
            $scope.getApiData();
        });
    };

}

})();

但是,当第二次调用$scope.getApiData时 - 手动或通过删除项目 - 它无法正确更新列表以反映API的状态,即使正确的结果是在HTTP响应中返回。列表保持不变,必须重新启动整个应用程序才能反映API中的数据。

HTML:

<table>
    <tr>
        <td>ID</td>
        <td>Item Name</td>
        <td>Price</td>
    </tr>
    <tr ng-repeat="product in productlist">
        <td>{{product.Id}}</td>
        <td>{{product.Name}}</td>
        <td>{{product.Price}}</td>
        <td><button ng-click="deleteProduct(product.Id)">X</button></td>
    </tr>
</table>

<button ng-click="getApiData()">Update</button>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="app/app.module.js"></script>
<script src="app/main.js"></script>

有问题解决这个问题。谢谢你的阅读!

2 个答案:

答案 0 :(得分:1)

事实证明该请求正在被缓存。我不知道它有多漂亮,但在请求中添加一个唯一参数将其排序。我在这里找到了解决方案:Angular IE Caching issue for $http

所以我的请求现在看起来像

Black_Litterman.get_data(cont, 0) 

哪个可以按照我的意愿运作。

答案 1 :(得分:0)

您应该将脚本放在head标记中,而不是body标记。

<!DOCTYPE html>
<html ng-app="app">
<head>
    <meta charset="utf-8" />
    <title>Products</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="app/app.module.js"></script>
    <script src="app/main.js"></script>
</head>
<body ng-controller="Products">
    <table>
        <tr>
            <td>ID</td>
            <td>Item Name</td>
            <td>Price</td>
        </tr>
        <tr ng-repeat="product in productlist">
            <td>{{product.Id}}</td>
            <td>{{product.Name}}</td>
            <td>{{product.Price}}</td>
            <td><button ng-click="deleteProduct(product.Id)">X</button></td>
        </tr>
    </table>

    <button ng-click="getApiData()">Update</button>

</body>
</html>