How to insert data taken from a JSON file and put in a list with AngularJS

1

app.js

(function(){

    var myApp = angular.module('loja', []);


    myApp.controller('CarrinhoController', ['$scope','$http', function($scope, $http){
        $scope.title = 'Lista de Produtos';


        $http.get('js/produtos.json').success(function(data){

            $scope.lista = data;

        });

    }]);



})();

productos.json

[

    {nome: 'Feijao', preco: 2.95},

    {nome: 'Arroz', preco:6.58},

    {nome:'Biscoito', preco:7.60}

];

HTML

<!DOCTYPE html>
<html ng-app="loja">
<head lang="en">
    <meta charset="UTF-8">
    <title>Teste Angular JS</title>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <script type="text/javascript" src="js/application/carrinho.js"></script>
</head>
<body>

    <div ng-controller="CarrinhoController">
        <h1>{{title}}</h1>

        <div class="produtos" ng-repeat="produto in lista">
            <ul>
              <li><strong>{{produto.nome}}</strong> : {{produto.preco}}</li>
            </ul>
        </div>

    </div>


</body>
</html>

I can not get product data from a JSON file by $http.get . The Firebug error is this:

  

[ngRepeat: dupes] link ?> p0 = product% 20in% 20list & p1 = string% 3A% 20 & p2 =% 22% 20% 22      at Error (native)

    
asked by anonymous 31.10.2014 / 04:53

2 answers

1

Change your HTML by adding track by $ index on your ng-repeat

<!DOCTYPE html>
<html ng-app="loja">
<head lang="en">
    <meta charset="UTF-8">
    <title>Teste Angular JS</title>
    <script type="text/javascript" src="js/angular.min.js"></script>
    <script type="text/javascript" src="js/application/carrinho.js"></script>
</head>
<body>

    <div ng-controller="CarrinhoController">
        <h1>{{title}}</h1>

        <div class="produtos" ng-repeat="produto in lista track by $index">
            <ul>
              <li><strong>{{produto.nome}}</strong> : {{produto.preco}}</li>
            </ul>
        </div>

    </div>


</body>
</html>
    
03.11.2014 / 18:25
0

In fact, your problem is the incorrect syntax of your JSON.

This one is correct:

[
    {"nome": "Feijao", "preco": 2.95},
    {"nome": "Arroz", "preco":6.58},
    {"nome":"Biscoito", "preco":7.60}
]

Here's the plunkr function.

    
31.10.2014 / 06:06