You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中从数组提取指定标题(首个标题)?

解决方案:直接通过数组索引访问,无需ng-repeat

完全没必要用ng-repeat来获取单个元素!ng-repeat是为遍历集合设计的,你要取数组的首个标题,直接通过数组索引访问就好,简单又高效。

基础写法

在你的模板里,直接用newsListings[0].title就能拿到第一个标题:

<div ng-controller="primaryController">
  <!-- 直接获取数组第一个元素的title属性 -->
  <h1>{{ newsListings[0].title }}</h1>
</div>

处理边界情况(避免数组为空时报错)

如果newsListings可能为空数组,直接访问[0].title会抛出错误,你可以用两种方式处理:

  1. 安全导航操作符(AngularJS 1.2+支持):

    <h1>{{ newsListings[0]?.title }}</h1>
    

    这个操作符会在newsListings[0]不存在时,自动停止后续属性访问,不会报错。

  2. 用ng-if先判断数组长度:

    <div ng-controller="primaryController">
      <h1 ng-if="newsListings.length > 0">{{ newsListings[0].title }}</h1>
      <!-- 数组为空时可以显示替代内容 -->
      <p ng-if="newsListings.length === 0">暂无新闻</p>
    </div>
    

为什么你之前的尝试没效果?

你用的number:0和json:0都是AngularJS的过滤器,它们的作用和取数组元素完全不相关:

  • number:0是用来格式化数字,去掉小数部分;
  • json:0是把数据转成JSON字符串,0参数在这里没有实际意义。

所以这些方法自然无法帮你拿到数组的首个标题啦~

内容的提问来源于stack exchange,提问作者Al-76

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:43:28