How to insert taken data from a JSON file and put into a list with Angularjs

Asked

Viewed 4,984 times

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;

        });

    }]);



})();

json products.

[

    {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’t get the product data from a JSON file from $http.get. The error in Firebug is this:

[ngRepeat:dupes] http://errors.angularjs.org/1.2.26/ngRepeat/dupes?>P0=product%20in%20lista&P1=string%3A%20&P2=%22%20%22 At Error (Native)

  • You can create a fiddle or plunkr with the problem?

  • Try to isolate this part of your code in another file to test, at first everything is ok!

2 answers

1

Change your HTML by adding track by $index in his 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>

0

Actually your problem is the incorrect syntax of your JSON.

This one is right:

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

Here’s the plunkr functioning.

  • Thank you. I spent all day yesterday trying to solve this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.