在Angular js脚本中循环

时间:2016-05-27 14:13:44

标签: angularjs

<?php
$total=0;
for($i1=1; $i1<=6; $i1++) {
    for($i2=$i1+1; $i2<= 6; $i2++) {
        echo $i1.", ".$i2."<br>";
        $total=$total+1;
    }
}
echo "<br>Total = ".$total;

请将此php代码转换为角度js代码

3 个答案:

答案 0 :(得分:1)

HTML:

<div ng-controller="MyCtrl">
  <div ng-repeat="pair in pairs">
    {{pair}}
  </div>
  Total = {{total}}
</div>

控制器:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.pairs = [];
  $scope.total = 0

  for (var i = 0; i <= 6; i++) {
    for (var j = i + 1; j <= 6; j++) {
      $scope.pairs.push(i + ", " + j);
      $scope.total = $scope.total + 1;
    }
  }
}

请参阅http://jsfiddle.net/scb08Lxe/

所以在一个文件中就是这样:

<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.pairs = [];
  $scope.total = 0

  for (var i = 0; i <= 6; i++) {
    for (var j = i + 1; j <= 6; j++) {
      $scope.pairs.push(i + ", " + j);
      $scope.total = $scope.total + 1;
    }
  }
}
</script>
<body ng-app="myApp">

<div ng-controller="MyCtrl">
  <div ng-repeat="pair in pairs">
    {{pair}}
  </div>
  Total = {{total}}
</div>

</body>
</html>

答案 1 :(得分:0)

您可以使用普通的Javascript进行此操作。

var total = 0;
for (var i = 0; i <= 6; i++) {
    for (var j = i+1; j <= 6; j++) {
        alert(i, j);
        total = total + 1;
    }
}
alert(total);

实际上,这是一个奇怪的问题。你想做什么?

答案 2 :(得分:0)

AngularJS也是Javascript,所以你可以这样做

PO Javascript

var total = 0;
for (var i = 0; i <= 6; i++) {
  for (var j = i+1; j <= 6; j++) {
    console.info(i, j);
    total = total + 1;
  }
}
console.info(total);

Angularjs方式:

对于angularJS,您可以查看上面的链接以获得相同的信息:     - https://docs.angularjs.org/api/ng/function/angular.forEach(控制器)     - https://docs.angularjs.org/api/ng/directive/ngRepeat(查看)