2017-02-08 4 views
-1

私はこのコードで助けが必要です。angularjs pass index throuhg指示文

<ul ng-init="round = 'round'"> 
    <li ng-repeat="mesa in mesas" ng-click="selected($index)"> 
    <div id="{{round}}">&nbsp;</div> 
    MESA {{mesa}} 
    </li> 
</ul> 


$scope.selected = function ($index){ 
    $scope.index.round = 'round1'; 
    } 

私は、CSSの名前を変更するにはクリックしたが、代わりにそれは私が列挙されていることを李さんのすべてを変更しているだけのLiことが必要です。

+0

あなたはどんなCSS名を参照していますか? – lealceldeiro

+2

この種の問題には '$ index'を使用しないでください。配列を繰り返す場合は、Angularで指定されたオブジェクトを使用できます。あなたのケースで '選択された(メサ)'。また、有効なHTMLでない同じ 'id 'を持つ多くの' divs'が得られます。ところで、あなたの機能は意味をなさない。あなたはそれが自己javascriptの基本的な理解を欠場しているように見えます。 – Michelangelo

答えて

1

変数roundをリピートループの外側で初期化しているため、式{{round}}は常にその特異な共有変数を指します。一度更新すると、ng-repeatのすべての子が更新されます。

私はあなたの質問を理解していれば、繰り返し内のdivのCSSクラスを変更しようとしていますか?あなたが、その場合には行うことができますことは、コントローラの範囲で選択したインデックスを格納し、また、あなたのCSSが構成されている方法に応じng-classの代わりng-ifを使用することができ

<ul> 
    <li ng-repeat="mesa in mesas" ng-click="select($index)"> 
    <div class="round1" ng-if="selectedIndex === $index">&nbsp;</div> 
    <div class="round" ng-if="selectedIndex !== $index">&nbsp;</div> 
    MESA {{mesa}} 
    </li> 
</ul> 


$scope.select = function ($index){ 
    $scope.selectedIndex = $index; 
} 

ループ内のインデックスに対して、その値をチェックしていますしかしその考えは同じです。

0

<html ng-app="app"> 
 

 
<head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script> 
 
    <style type="text/css"> 
 
    \t .round { 
 
    \t \t background: green; 
 
    \t } 
 
    \t .round1 { 
 
    \t \t background: blue; 
 
    \t } 
 
    </style> 
 
</head> 
 

 
<body ng-controller="controller"> 
 
    <ul> 
 
     <li ng-repeat="mesa in mesas" ng-click="selected($index)" ng-class="[index[$index].round]"> 
 
      <div id="{{ index[$index].id }}">&nbsp;</div> 
 
      MESA {{ mesa }} 
 
     </li> 
 
    </ul> 
 

 
</html> 
 
<script type="text/javascript"> 
 
angular.module('app', []) 
 
    .controller('controller', controller); 
 

 
controller.$inject = ['$scope']; 
 

 
function controller($scope) { 
 
    $scope.mesas = ['1', '2', '3']; 
 
    $scope.index = [{ 
 
     id: '1', 
 
     round: 'round' 
 
    }, { 
 
     id: '2', 
 
     round: 'round' 
 
    }, { 
 
     id: '3', 
 
     round: 'round' 
 
    }]; 
 

 
    $scope.selected = function($index) { 
 
     $scope.index[$index].round = $scope.index[$index].round === 'round' ? 'round1' : 'round'; 
 
    } 
 
} 
 
</script>

私はuがfor¿探して何だと思いますか?