0

私は学校プロジェクトに取り組んでいます。 ng-repeatでいくつかの行を作成しました。私は「addElementsByClassName」でそれらを追加したい場合は今にarrayLengthはまだこれは私のhtmlである0繰り返し要素を角度に配列に追加する方法

次のようになります。

<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アドバイス

しかし、私はあなたが程度はJavaScriptで命名規則、グッドプラクティスをangular.js読み、そしてあなたのJSONの構造について考えをお勧めします。例えば

代わりに$スコープ使用の
  1. controllerAs View Syntax

  2. がルールに従ってください:JavaScript Style Guide and Coding Conventionsあなたは角度ダイジェスト・サイクルを実行するための任意の時間を与えていない

0

私はその配列内に自分の行を入れたいので、後でそれらを使って何かできるのです。

「後で」使用する直前に行数を取得してみてください。更新する必要があります。 そうでない場合は、$ scope。$$ apply()を使用してダイジェストサイクルを誘導してみてください。

関連する問題