将json文件提取到angularjs中

时间:2017-01-16 16:31:30

标签: javascript angularjs arrays json

我正在尝试在我的本地服务器上获取一个json文件,其中我存储了很少的数组。我正在尝试通过使用代码运行的$ http服务来实现此目的:

(function(){
    var app = angular.module('store', ['store-products']);
    app.controller('StoreController',['$http', function($http){
        var store = this;
        store.products = [];
        $http.get('products.json').success(function(data){
            store.products = data;
        })
})();

我的products.json文件:

[ {
    "name" : "Lasagna",
    "price" : 250,
    "images":[{"full":"images/lasagne.jpg"}],
    "Description":"Lasagne are wide, flat-shaped pasta, and possibly one of the oldest types of pasta.The word 'lasagne', and, in many non-Italian languages, the singular 'lasagna', can also refer to a dish made with several layers of lasagne sheets alternated with sauces and various other ingredients.",
    "canPurchase": true,
    "Reviews":[]

            },
            {
    "name":"Shawarma",
    "price":300,
    "images":[{"full":"images/shawarma.jpg"}],
    "Description":"Shawarma or Shawurma  is a Levantine meat preparation, where lamb, chicken, turkey, beef, veal, buffalo meat, or mixed meats are placed on a spit (commonly a vertical spit in restaurants), and may be grilled for as long as a day.Shavings are cut off the block of meat for serving, and the remainder of the block of meat is kept heated on the rotating spit. Shawarma can be served on a plate (generally with accompaniments), or as a sandwich or wrap. Shawarma is usually eaten with tabbouleh, fattoush, taboon bread, tomato, and cucumber. Toppings include tahini, hummus, pickled turnips, and amba",
    "canPurchase": true,
    "Reviews":[]
    }]

我的HTML代码:

<!doctype html>
<html ng-app="store">
<head>
     <link rel="stylesheet" href="styles/bootstrap.min.css">
</head>
<body ng-controller="StoreController as store">
    <h1 align="center"><ul>Food Junkie</ul></h1>
    <h2 align="center">-It's all gonna be alright-</h2> 
    <ul class="list-group">
        <li class="list-group-item" ng-repeat ="product in store.products">
            <product-title></product-title>
            <product-images></product-images>
            <button ng-show="product.canPurchase"><img src="images/cart_64x64.jpg"/></button></br>
            <product-panel></product-panel>
        </li>
    </ul>

    <script type="text/javascript" src="scripts/angular.min.js"></script>
    <script type="text/javascript" src="scripts/ang.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以像这样访问它,但您的网址是错误的。如果json文件在根目录中,请使用$http.get('product.json'),否则不要以短划线/开头,即:$http.get('path/to/product.json')

请注意您的Angular版本,因为最新版本替换了$http.success()以及.error()

.then() .catch()angular.module("app",[]) .controller("myCtrl",function($scope){ $scope.tags = ["some tag", "some other tag"]; });