如何通过计算表达式来创建自定义HTML ID

时间:2015-04-21 14:38:10

标签: javascript html angularjs

我尝试制作一个版本的" tic tac toe"使用AngularJS并尽可能简约。我的问题的唯一解决方案是为每个按钮分配一个唯一的ID(f + i)。

HTML

<table>
    <tr ng-repeat="f in [5,10,15]">
        <!-- numbers chosen for unique combos-->
        <td ng-repeat="i in [0,1,2]">
            <button  ng-click="toTrue()" >
                <div >
                    {{getXO()}} 
                </div>
            </button>
        </td>
    </tr>
</table>

的JavaScript

 $scope.XObool=false;
 $scope.toTrue = function() {
     if(!$scope.XObool){
         $scope.XObool=true; 
     }
     else if($scope.XObool) {
         $scope.XObool=false;
     }
 };
 $scope.getXO = function(){
     if($scope.XObool){
         return 'X';
     }
     else {
         return 'O';
     }
 };

3 个答案:

答案 0 :(得分:5)

ng-repeat为您提供了几个可以使用的变量,即$index。在你的情况下,你会想要像:

<button id="{{$index}}" ...>

有关ng-repeat docs的更多信息。

第二个选项

使用fi变量创建唯一ID。

<table ng-app>
  <tr ng-repeat="f in [5,10,15]" data-id="{{$index}}">
    <td ng-repeat="i in [0,1,2]">
      <button id={{'id' + (i+f)}} ng-click="toTrue()">
        {{'id'+(i+f)}} 
      </button>
    </td>
  </tr>
</table>

这是demo

答案 1 :(得分:0)

您无需为每个按钮指定唯一ID。

相反,您可以将f和i变量传递到函数中以跟踪电路板状态:

<table>
        <tr ng-repeat="f in [0,1,2]">
            <!-- numbers chosen for unique combos-->
        <td ng-repeat="i in [0,1,2]">
            <button ng-click="setState(f, i)">
            <div >
                {{ getXO(f,i) }} 
            </div>
        </button>
        </td>

        </tr>
    </table>

在这里工作小提琴:http://jsfiddle.net/m76w3kf5/

答案 2 :(得分:0)

尝试使用{{}}或$ index

进行标记绑定
<div id="{{someObject.id}}" class="some-class" ng-repeat="f in [ array ]">
..
</div>

或带有$ index的稍微扩展的示例,列出数组中的缩略图,其中点击按索引引用位置

<tr ng-repeat="array in thumbnails track by $index">
  <td ng-repeat="object in array track by object.id" 
      ng-click="tableClickHandler($index, object)">

    <img class="user-thumbnail" src="{{object.src}}">

  </td>
</tr>