How to add a repeated element to an array in Angular

252 views Asked by At

I'm working on a schoolproject. I created some lines with ng-repeat. Now when I want to add them with 'addElementsByClassName' the arraylength will still be 0.

This is in my html:

<tr class = "ingredient" ng-repeat = "i in data.Ingredients">
    <td>{{ i.Ingredient.Name }}</td>
    <td>{{ i.Ingredient.Amount_g }}</td>
</tr>

This is in my controller:

    $scope.allIngredients = [];
    $scope.dashboard = MainService.getDashboard ();

    $scope.dashboard.then (function (data) { //receive the data from a server via MainService
        $scope.data = data;
        $scope.allIngredientRows = document.getElementsByClassName ('ingredient');
        console.log ($scope.allIngredients.length);
    });

I want my rows inside that array so I can do something with them later. But now the length of the array remains 0.

2

There are 2 answers

0
dev8080 On

You are not giving the Angular digest cycle any time to run.

I want my rows inside that array so I can do something with them later.

Try retrieving the row count right before that 'later' use. It should be updated. If not, try using $scope.$$apply() to induce a digest cycle.

0
Jarek On

#1 Your approach is wrong. You should operate on data, not on the html elements. Try this way:

HTML:

<tr ng-repeat="item in ingredients">
    <td>{{ item.Ingredient.Name }}</td>
    <td>{{ item.Ingredient.Amount_g }}</td>
</tr>

Controller:

$scope.ingredients = [];

MainService.getDashboard().then (function (data) {
    $scope.ingredients = data.Ingredients;

    console.log ($scope.ingredients.length); // Amount of your ingredients
});

When you want to add more items, use:

$scope.ingredients.push(newIngredient);

or

$scope.ingredients = $scope.ingredients.concat(newIngredients);

#2 Advice

But I recommend you read about angular.js good practices, naming conventions in javascript, and think about your json structure.

For example:

  1. Instead of $scope use: controllerAs View Syntax

  2. Follow the rules: JavaScript Style Guide and Coding Conventions