-1

I want to fill a table with tr's and td's with a loop in angular. I have used PHP to fill my table with the tr's and td's:

for($j = 1; $j <= 8; $j++){
    echo "<tr>";
    for($i = 1; $i <= 20; $i++){    
        if($string[$k] == "#"){
            echo "<td id='$k'>#</td>";
        }elseif($string[$k] == "&"){
            echo "<td class='click' val='water' id='$k'>&</td>";
        }else{
            echo "<td class='click' id='$k'><a href='#'></a></td>";
        }
        $k++;
    }
    echo "</tr>";
}

How can I accomplish the same thing using angular?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user500468
  • 1,183
  • 6
  • 21
  • 36

3 Answers3

0

In order for you to achieve this you need to have a element in an array so you can use ng-repeat to fill the list. Have a look here Angular JS - ng-repeat and loop conditions

Community
  • 1
  • 1
user3811714
  • 286
  • 2
  • 8
  • 21
0

The paradigm described in your code is very non-angular. In your code, you are using server-side code to assemble markup. The angular approach would be to use server-side code to send data to the client (via AJAX, or inlined JSON or javascript on load) and then have angular assemble the markup.

There are many reasons some people prefer this approach, but the one that stands out to me is: you'll probably have javascript interacting with this markup in any case, but angular allows the server to be agnostic about the page's interactive behavior. Better separation of concerns.

To answer your question more directly, do something like this (shooting from the hip here):

<script>
myAngularApp.controller('MyController', ['$scope', function($scope) {
    $scope.myTableData = <?php echo $myTableJSON; ?>;
}]);
</script>

<table ng-controller="MyController">
    <tbody>
        <tr ng-repeat="row in myTableData">
            <td ng-repeat="cell in row">{{ cell.text }}</td>
       </tr>
   </tbody>
</table>
Chris
  • 6,805
  • 3
  • 35
  • 50
0

I suggest you do not use angular for this. Angular is more high-level framework. You should write this peace of code as a standalone non-angular module and wrap with anular's directive for data-binding.

Unrealsolver
  • 143
  • 4