【问题标题】:I'm trying to print an array using a loop in Javascript in Angular JS我正在尝试在 Angular JS 中使用 Javascript 中的循环打印数组
【发布时间】:2015-05-12 02:57:14
【问题描述】:

我正在尝试从对象的属性中打印出每个数组项:

{
        position:"Finance Office Assistant",
        employer:"Washtenaw County Finance Department",
        location:"Ann Arbor, MI",
        start_date:"2012",
        current: false,
        end_date:"2012",
        duties: [
            "Item 1",
            "Item 2",
            "Item 3" 
        ]
    },  

此对象与其他几个对象位于一个数组中。我正在尝试创建一个函数,该函数循环遍历所有对象并在无序列表中打印出 duties 数组项,其中包含列表项和数组项的确切数量。

这是我为完成任务而尝试编写的函数

$scope.dutyList = function() {
    var arrayLength = $scope.duties.length;
    while (arrayLength > 0) {
        console.log("dutyList run")
        document.write("<li> {{ dutyList }} </li>");
        --arrayLength;
    }
}

【问题讨论】:

  • 你从你的代码中看到了什么结果,它与你想要的有什么不同?

标签: javascript arrays angularjs loops while-loop


【解决方案1】:

您不需要一个函数来处理这样的显示数据。 Angular 的 ngRepeat 就是为此而生的。要访问数据集的第二级,您可以在无序列表中嵌套两个重复。第一个(在 div 中)重复数据的第一层,并暴露第二层,在 &lt;li&gt; 标记中重复:

  <ul>
      <div ng-repeat="d in data">
        <li ng-repeat="duty in d.duties">{{duty}}</li>  
      </div> 
  </ul>

Plunker

【讨论】:

  • 之前尝试过嵌套,语法错误。这很好用,谢谢!
【解决方案2】:

一般来说,在使用 Angular 之类的框架时,您不希望直接写入文档。相反,您应该使用内置的模板系统和指令来呈现您的页面。

我在这里对最终目标进行了一些假设,但是,假设控制器可以访问对象数组并附加到范围,您可以使用以下内容打印每个职位的无序列表职责.

angular.module('myApp', []).controller('myCtrl', function($scope){
  $scope.foo = [{
        position:"Finance Office Assistant",
        employer:"Washtenaw County Finance Department",
        location:"Ann Arbor, MI",
        start_date:"2012",
        current: false,
        end_date:"2012",
        duties: [
            "Item 1",
            "Item 2",
            "Item 3" 
        ]
    }, {
        position:"Another Position",
        employer:"Another Employer",
        location:"Ann Arbor, MI",
        start_date:"2012",
        current: false,
        end_date:"2012",
        duties: [
            "2nd Object, Item 1",
            "2nd Object, Item 2",
            "2nd Object, Item 3" 
        ]
    }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller='myCtrl'>
  <div ng-repeat='bar in foo'>
    <h1>{{ bar.position }}</h1>
    <ul>
      <li ng-repeat='duty in bar.duties'>
        {{ duty }}
      </li>
    </ul>
  </div>
</div>

【讨论】:

  • 这仅在您拥有一个对象的显示职责时才有效。
  • @tpie 你是对的 - 我错过了问题中的那个细节。固定。
  • 谢谢你,我刚刚进入 Angular,我肯定想得太难了!
猜你喜欢
  • 2020-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-03
  • 1970-01-01
  • 1970-01-01
  • 2015-08-09
相关资源
最近更新 更多