Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a custom HTML id by evaluating an expression

I try to make a version of "tic tac toe" with AngularJS and be as minimalistic as possible. The only solution for my problem is to assign every button a unique 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';
     }
 };
like image 955
Mike Fellner Avatar asked Apr 21 '15 14:04

Mike Fellner


1 Answers

ng-repeat gives you several variables to work with, namely $index. In your case you'll want something like:

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

More info on the ng-repeat docs.

Second Option

Use the f and i variables to create unique IDs.

<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>

Here's a demo.

like image 195
Brett DeWoody Avatar answered Oct 03 '22 09:10

Brett DeWoody