0

I have my data in products.json like this:

{
"products":[
{
     "name":"Antricot de vita",
     "calorii":236,
     "proteine":17.4,
     "lipide":18.5,
     "carbohidrati":0,
     "fibre":0
  },
  {
     "name":"Muschi de vita crud",
     "calorii":215,
     "proteine":19,
     "lipide":15,
     "carbohidrati":0,
     "fibre":0
  },
  {
     "name":"Albus de ou",
     "calorii":52,
     "proteine":10.9,
     "lipide":0.2,
     "carbohidrati":0.7,
     "fibre":0
  }
 ]
}

So, as you can see I have an array called products which comes with some objects each one having 6 properties. I have a table in which every tr has 6 tds with the properties mentioned. When clicked the button on right of each tr I want that tr to be deleted. The problem occures when I have to delete an element from the table. I have tried a splice function which seems not to work. Please help me fix this issue. Thank you so much! PS: The push function does work!

Below is my code: app.js

    var app = angular.module('Calorii', []);
    app.factory('products', ['$http', function($http) {
      return $http.get('products.json')
        .success(function(data) {
          return data;
        })
        .error(function(data) {
          console.log("error");
          return data;
        });
    }]);
    app.controller('HomeController', ['$scope', 'products', function($scope, products) {
      products.success(function(data) {
        $scope.produse = data;
        $scope.predicate = 'name';
        $scope.reverse = false;
        $scope.order = function(predicate) {
          $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
          $scope.predicate = predicate;
        };
        $scope.removeItem = function(item) {
          var index = $scope.produse.products.indexOf(item);
          $scope.produse.products.splice(index, 1);
        };
        $scope.add = function() {
          if (angular.isDefined($scope.name) && $scope.name != '' && $scope.calorii >= 0 &&
            $scope.proteine >= 0 && $scope.lipide >= 0 && $scope.carbohidrati >= 0 &&
            $scope.fibre >= 0) {
            $scope.produse.products.push({
              name: $scope.name,
              calorii: $scope.calorii,
              proteine: $scope.proteine,
              lipide: $scope.lipide,
              carbohidrati: $scope.carbohidrati,
              fibre: $scope.fibre
            });
            $scope.name = '';
            $scope.calorii = '';
            $scope.proteine = '';
            $scope.lipide = '';
            $scope.carbohidrati = '';
            $scope.fibre = '';
          } else {
            alert("Unul sau mai multe spatii nu a fost completat");
          }
        };
      });
    }]);
    app.directive('myElement', function() {
      return {
        scope: {
          item: '=myElement'
        },
        restrict: 'EA',
        template: '<td class="left">{{ item.name }}</td><td>{{ item.calorii }}</td><td class=>{{ item.proteine }}</td><td class>{{ item.lipide }}</td><td class=>{{ item.carbohidrati }}</td><td class=>{{ item.fibre }}</td><td><button ng-click="removeItem(product)"><img src="images/remove.png"/></button></td>'
      };
    });

index.html

<!DOCTYPE html>
<html>
<head>
  <title>Calorii</title>
    <script src="js/shared/angular.js"></script>
    <script src="js/shared/jquery-2.2.2.min.js"></script>
   <link href="css/main.css" rel="stylesheet" />
</head>
<body ng-app="Calorii" ng-controller="HomeController">
  <div class="main">
    <div id="header">
      <img src="images/kilocalorii-logo.png">
      <ul id="nav">
        <li id="menulink"><a href="index.html" title="Tabelul de calorii"></a></li>
        <li id="genlink"><a href="#" title="Despre tabelul de calorii"></a></li>
        <li id="searchspot">
        <form id="searchform" class="searchform">
          <input id="s" type="search" ng-model="query">
        </form>
        </li>
      </ul>
      <div id="rapidfindlabel"></div>
    </div>
        <div class="content">
          <a href="#" class="noSort" ng-click="predicate=''">Doresc tabelul nesortat</a>
          <table class="tabelcalorii"> 
          <tbody>
          <tr>
            <th class="left">
            <a href="#" class="sort" ng-click="order('name')">Aliment</a>
            <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
            </th>
            <th>
              <a href="#" class="sort" ng-click="order('calorii')">Calorii</a>
              <span class="sortorder" ng-show="predicate === 'calorii'" ng-class="{reverse:reverse}"></span>
            </th>
            <th>
              <a href="#" class="sort" ng-click="order('proteine')">Proteine</a>
              <span class="sortorder" ng-show="predicate === 'proteine'" ng-class="{reverse:reverse}"></span>
            </th>
            <th>
              <a href="#" class="sort" ng-click="order('lipide')">Lipide</a>
              <span class="sortorder" ng-show="predicate === 'lipide'" ng-class="{reverse:reverse}"></span>
            </th>
            <th>
              <a href="#" class="sort" ng-click="order('carbohidrati')">Carbohidrati</a>
              <span class="sortorder" ng-show="predicate === 'carbohidrati'" ng-class="{reverse:reverse}"></span>
            </th>
            <th>
              <a href="#" class="sort" ng-click="order('fibre')">Fibre</a>
              <span class="sortorder" ng-show="predicate === 'fibre'" ng-class="{reverse:reverse}"></span>
            </th>
            <th>Scoate din lista</th>
          </tr>
          <tr ng-repeat="product in produse.products | orderBy:predicate:reverse | filter:query" my-element="product"></tr>
        </tbody>
        </table>

        <p class="more"><strong>Nota:</strong> Toate valorile nutritive sunt calculate pentru o cantitate de 100g.</p>
        <p style="margin-left:5px">Daca nu ai gasit alimentul cautat, adauga-l completand tabelul de mai jos:</p>

        <table cellspacing="1" cellpadding="4" width="100%" class="add_table">
        <tbody>
          <tr>
            <td class="add_name"><b>Aliment:</b></td>
            <td class="add_value"><input type="text" ng-model="name" placeholder="Introdu numele alimentului" style="width: 215px"><br></td>
            <td><span class="sugestie">exemplu: <b>Pate de porc cu verdeturi Bucegi</b></span></td>
          </tr>
          <tr>
            <td class="add_name" valign="top"><b>Calorii:</b></td>
            <td class="add_value"><input type="number" ng-model="calorii" placeholder="Introdu numarul de calorii" style="width: 215px"><br></td>
            <td><span class="sugestie">completarea numarului de calorii este obligatorie</span></td>
          </tr>
          <tr>
            <td class="add_name" valign="top"><b>Proteine:</b></td>
            <td class="add_value"><input type="number" ng-model="proteine" placeholder="Introdu numarul de proteine" style="width: 215px"><br></td>
            <td><span class="sugestie">completarea numarului de proteine este obligatorie</span></td>
          </tr>
          <tr>
            <td class="add_name" valign="top"><b>Lipide:</b></td>
            <td class="add_value"><input type="number" ng-model="lipide" placeholder="Introdu numarul de lipide" style="width: 215px"><br></td>
            <td><span class="sugestie">completarea numarului de lipide este obligatorie</span></td>
          </tr>
          <tr>
            <td class="add_name" valign="top"><b>Carbohidrati:</b></td>
            <td class="add_value"><input type="number" ng-model="carbohidrati" placeholder="Introdu numarul de carbohidrati" style="width: 215px"><br></td>
            <td><span class="sugestie">completarea numarului de carbohidrati este obligatorie</span></td>
          </tr>
          <tr>
            <td class="add_name" valign="top"><b>Fibre:</b></td>
            <td class="add_value"><input type="number" ng-model="fibre" placeholder="Introdu numarul de fibre" style="width: 215px"><br></td>
            <td><span class="sugestie">completarea numarului de fibre este obligatorie</span></td>
          </tr>
              <button class="submit" ng-click="add()">ADAUGA</button>
          </tbody>
        </table>
        </div>
    </div>

     <!-- Modules -->
    <script src="js/app.js"></script>


 </body>
</html>

I know there is plenty of code above, but if you don't mind I would appreciate if you could explain shortly how to call splice function on my json products. Thanks again!

4
  • You should really need to isolate issues with fewer code if you want answers here... Commented May 4, 2016 at 19:51
  • Instead of relying in the indexOf function to get the item index, you should pass it from the front. ng-click="removeItem($index)" and then in your controller use that param as index to splice Commented May 4, 2016 at 19:58
  • If you put a alert or console.log in your function removeItem it works? I think you have a problem in your directive, that doesn't find your controller scope. Commented May 4, 2016 at 19:58
  • @FelippeDuarte it seems like not Commented May 4, 2016 at 20:16

2 Answers 2

3

indexOf sometimes fails to find the index of an object in an array. Either you use lodash or underscore to do so, or change your approach:

<td><a ng-click="removeItem($index)">Remove</a></td>

Ctrl

$scope.removeItem = function(index) {
   $scope.produse.products.splice(index, 1);
}

$index as available to you when using ng-repeat in angular.

Sign up to request clarification or add additional context in comments.

8 Comments

Make sure you enter that function. Add a console.log inside or some shit to make sure it's calling the right function
Nothing is displayed although I added console.log into that function
Can you put together some plnkr or codepen so we can check?
Here you go. You have to call the function with $parent.removeItem($index). plnkr.co/edit/CLWlOp4M7uWhAtAM6tBs?p=preview
I see... Now as I was trying to check it I noticed different items are being removed when clicked on 'Remove' instead of the one selected(sometimes it also happens to be the right one). How come?
|
1

You have a problem with myElement directive.

ng-click="removeItem(product)" 

it should be

ng-click="removeItem(item)".

4 Comments

The problem is directive isolated scope. So you need to change the directive not to use isolated scope. This is the reason why your function is never called
How can I change it? I mean, what needs to be modified?
Change template directive as: template: '<td class="left">{{ item.name }}</td><td>{{ item.calorii }}</td><td class=>{{ item.proteine }}</td><td class>{{ item.lipide }}</td><td class=>{{ item.carbohidrati }}</td><td class=>{{ item.fibre }}</td><td><button ng-click="$parent.removeItem(item)">Remove</button></td>'
Works now. Thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.