无法迭代

时间:2016-11-17 11:28:44

标签: javascript angularjs

我在制定ng-repeat指令时遇到了问题,因为我是初学者,无法自行解决。



var myModule = angular.module("myFirst",[]);

myModule.controller("cont", function($scope){
var employees = [
{name: "Manju", age :"23", rank:"2"},
{name: "SivaSankari", age :"23", rank:"1"},
{name: "Gayathri", age :"23", rank:"1"},
];
$scope.employees = employees;
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html  ng-app="myFirst">
  <head>
    <title> My workout|ngRepeat
    </head>
<body>
<div ng-controller="cont">
<table>
<thead>
<th>Name</th>
<th>Age</th>
<th>Postions</th>
</thead>
<tbody>
<tr ng-repeat="x in employees">
<td>{{employees.name}}</td>
<td>{{employees.age}}</td>
<td>{{employees.position}}</td>
</tr>
</tbody>
</table>

</div>

</body>
  <html>
&#13;
&#13;
&#13;

另外我对关键是x有疑问。可以给任何关键值吗? 任何人都可以帮我解决和理解吗? 感谢。

6 个答案:

答案 0 :(得分:0)

应该是

<td>{{x.name}}</td>
<td>{{x.age}}</td>
<td>{{x.position}}</td>

答案 1 :(得分:0)

您应该访问 x 的属性,而不是 employee 数组

<td>{{x.name}}</td>
<td>{{x.age}}</td>
<td>{{x.position}}</td>

答案 2 :(得分:0)

您将x定义为您正在迭代的员工。所以重复部分应该是:

<tr ng-repeat="x in employees">
<td>{{x.name}}</td>
<td>{{x.age}}</td>
<td>{{x.position}}</td>
</tr>

答案 3 :(得分:0)

<强>第一

您必须使用x代替employees,因为employees是您的数组而x是当前项目

<强>第二

您试图访问对象中不存在的属性position。你应该致电rank

var myModule = angular.module("myFirst", []);

myModule.controller("cont", function($scope) {
  var employees = [{
    name: "Manju",
    age: "23",
    rank: "2"
  }, {
    name: "SivaSankari",
    age: "23",
    rank: "1"
  }, {
    name: "Gayathri",
    age: "23",
    rank: "1"
  }, ];
  $scope.employees = employees;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myFirst">

<body>
  <div ng-controller="cont">
    <table>
      <thead>
        <th>Name</th>
        <th>Age</th>
        <th>Postions</th>
      </thead>
      <tbody>
        <tr ng-repeat="x in employees">
          <td>{{x.name}}</td>
          <td>{{x.age}}</td>
          <td>{{x.rank}}</td>
        </tr>
      </tbody>
    </table>

  </div>

</body>
<html>

答案 4 :(得分:0)

当您使用ng-repeat="x in employees"时,这意味着您在每次迭代时都会说明将项目分配给x,这就是为什么您不能使用除x以外的任何其他变量的原因<td>{{x.name}}</td> <td>{{x.age}}</td> <td>{{x.position}}</td>

ngRepeat

答案 5 :(得分:0)

我在标题标签中没有理解你的<tr ng-repeat="x in employees"> ,但你的表格声明没什么意义。

x

表示对于数组employees中的每个元素(以下称为td),重复此元素即。表格行。 (确保你真正想做的事)

因此,在<td>{{x.name}}</td> 内,你必须写 -

x
  

另外我对关键是x有疑问。可以提供任何关键值吗?

如果您想说是否可以拨打<tr ng-repeat="singleEmployee in employees"> <td>{{singleEmployee.name}}</td> 其他任何内容,那么您可以。 E.g。

$response