0

我正在学校项目中工作。我用ng-repeat创建了一些行。现在,当我想他们“addElementsByClassName”添加arraylength仍然是0。如何向Angular中的数组添加重复元素

这是我的html:

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

这是在我的控制器:

$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); 
    }); 

我想我的行在该数组中,所以我可以稍后再用它们做些事情。但现在阵列的长度保持为0.

+1

document.getElementsByClassName(“成分”)会给你所有谁拥有类成分的元素的数组。你需要检查服务函数中的响应数据回调 – Deep

+0

是的,但我想修改行,而不是数据。 – JordyM

+0

你的数据对象 - 或者其他什么 - 看起来像什么? – IAmDranged

回答

1

#1你的方法是错误的。 您应该对数据进行操作,而不是对html元素进行操作。 试试这个方法:

HTML:

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

控制器:

$scope.ingredients = []; 

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

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

当你想添加更多的项目,使用方法:

$scope.ingredients.push(newIngredient); 

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

#2咨询

但我建议你阅读angular.js良好做法,在JavaScript的命名约定,想想你的JSON结构。

例如:

  1. ,而不是$范围使用:controllerAs View Syntax

  2. 遵循的规则:JavaScript Style Guide and Coding Conventions

0

你是不是给角消化周期的任何时间运行。

我希望我的行在该数组内,以便稍后可以对它们做些什么。

尝试检索一行“后”在使用前右边计数。它应该更新。 如果不是,请尝试使用$ scope。$$ apply()来引发摘要循环。