2016-09-12 7 views

答えて

1

アレイ用(NG-リピート)書き方を知りたい私のJavascriptのコードですグローバル変数。変数をそのまま残して、ループを呼び出します。後でhtmlコードでグローバル変数を使用するだけです。

あなたはそれがどのように動作するかを理解するように、私はクールなスニペットを作った:

angular.module('demo', []) 
 

 
.controller('Ctrl', ['$scope', function ($scope) { 
 
    $scope.inputs = []; 
 

 
    var a = ['name1', 'name2', 'name3']; 
 
    var b = [133,233,456]; 
 

 
    //this code has to be called somewhere else. It might be part of a function. 
 
    for(var i=0; i < a.length; i++){ 
 
    $scope.inputs.push({name:a[i],value:b[i]}); 
 
    } 
 
    
 
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="demo"> 
 
    <div ng-controller="Ctrl"> 
 
     <ul> 
 
      <li ng-repeat="item in inputs"> 
 
       <input ng-model="item.name"/> 
 
      </li> 
 
     </ul> 
 
     
 
     <!--This is only to display the content of $scope.inputs --> 
 
     <pre>{{inputs | json}}</pre> 
 
    </div> 
 
</div>

1

をあなたのJSが無効である、長さ1の配列が生成されます。このと交換してください:

$scope.inputs=[]; 
for(var i=0;i<a.length;i++){// be sure that a.length >=b.length 
    $scope.inputs.push({name:a[i],value:b[i]}); // push will add new entry to your inputs array. 
} 

ザ・あなたはngのリピートでそれを使用することができます。

<div ng-repeat="entry in inputs"> {{entry.name}} : {{entry.value}} </div> 
0

あなたのhtml

に表示されているスコープを使用して、コントローラ内の配列を、持っている場合
angular.module('appName').controller('mainCtrl', mainCtrl); 

function mainCtrl($scope) { 
    $scope.inputs = [ 
     key: value, 
     ... 
    ]; 
} 

あなたのhtmlでは、コントローラーの範囲内でng-repeatを使用します。あなたは<ul>リスト、div、選択ドロップダウンとhtmlでより多くの私たちが書く

<div ng-controller="mainCtrl"> 
    <ul> 
      <li ng-repeat="item in inputs">{{item.key}} <!-- Prints 'value' --></li> 
    </ul> 
</div> 
関連する問題