如何使用ejs模板在从angularjs控制器接收的整数数组上运行for循环

时间:2014-07-26 08:00:25

标签: angularjs for-loop ejs

尝试使用带有ejs的angularjs在angularjs控制器上的ejs模板上接收的整数数组上运行for循环。

以下是代码:

<div class="form-group" ng-controller="MyController as myCtrl">
    <div><label>Trying to run the for loop on {{myCtrl.getMyIntegerArray()}} array</label></div>
    <select class="form-control  input-xsmall inline">
        <option>Year</option>
        <% for(var i=0; i <= {{myCtrl.getMyIntegerArray().length}}; i++) { %>
        <option>{{myCtrl.getMyIntegerArray()[i]}}</option>
        <% } %>
    </select>
</div>

有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

此处无需使用ejs,angularjs有自己的模板引擎。

您可以使用ng-repeat来实现您想要的效果:

<select class="form-control input-xsmall inline">
  <option>Year</option>
  <option ng-repeat="value in myCtrl.getMyIntegerArray()">{{value}}</option>
</select>

但最好将结果存储在控制器中这样的$scope中:

app.controller('MainCtrl', function($scope) {
  this.getMyIntegerArray = function () {
    return [1234, 5678, 9012, 3456];
  };

  $scope.myIntegerArray = this.getMyIntegerArray();
});

并在html中:

<select class="form-control input-xsmall inline">
  <option>Year</option>
  <option ng-repeat="value in myIntegerArray">{{value}}</option>
</select>

示例plunker: http://plnkr.co/edit/IttzGJfOzYdP9Du0uAPh?p=preview

希望这有帮助。