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

点击AngularJS ng-repeat项后模态框无法显示选中内容的问题

解决模态框无法显示选中产品信息的问题

嘿,我帮你找到了两个关键问题,这就是模态框显示空白的原因:

1. 函数参数引用错误

你的showProduct函数接收的参数是product,但函数内部却写成了products.name和products.image(多了个s),这会导致无法正确获取选中产品的信息,selectedProductName和selectedProductImage实际上都是undefined,所以模态框里没有内容。

2. 模态框位置错误

你把模态框放在了ng-repeat="category in categories"的循环内部,这会导致每个分类都生成一个ID为myModal的模态框。HTML中ID是唯一标识,点击时浏览器只会触发第一个匹配的模态框,而且冗余的模态框也会造成DOM混乱。


修正后的代码

AngularJS 控制器代码

var data = [ 
  { 
    categoryName: "Building Materials", 
    products: [ 
      { name: "Corrugated Zinc Sheets", image: "images/roofing.jpg", price: 200 }, 
      { name: "Bathtub", image: "images/bathtub.jpeg", price: 2000 } 
    ] 
  }, 
  { 
    categoryName: "Solar Products", 
    products: [ 
      { name: "330W Solar Panel", image: "images/solar2.jpg", price: 5500 }, 
      { name: "150W Solar Panel", image: "images/solar.jpg", price: 3500 } 
    ] 
  } 
];

app.controller("productsCtrl", function($scope){
  $scope.categories = data;

  $scope.showProduct = function(product) {
    // 修正变量名:products → product
    $scope.selectedProductName = product.name;
    $scope.selectedProductImage = product.image;
  }
});

HTML 代码

<div class="container"> 
  <h1>{{categories[1].categoryName}}</h1> <!-- 修正原代码的小错误:取第二个分类的名称 -->
  <div class="row" ng-repeat="category in categories"> 
    <h2>{{category.categoryName}}</h2> 
    <div class="col-sm-6" ng-repeat="product in category.products track by $index"> 
      <div class="panel"> 
        <img ng-src="{{product.image}}" ng-click="showProduct(product)" data-toggle="modal" data-target="#myModal"> 
        <h6 ng-click="showProduct(product)" data-toggle="modal" data-target="#myModal">{{product.name}}</h6> 
        <p>R{{product.price}}</p> 
      </div> 
    </div> 
  </div> 

  <!-- 将模态框移到ng-repeat循环外面,确保全局只有一个模态框 -->
  <!-- More info Modal --> 
  <div class="modal fade" id="myModal" role="dialog"> 
    <div class="modal-dialog"> 
      <!-- Modal content--> 
      <div class="modal-content"> 
        <div class="modal-header"> 
          <button type="button" class="close" data-dismiss="modal">&times;</button> 
          <h4 class="modal-title" style="color: #0091EA;">{{selectedProductName}}</h4> 
        </div> 
        <div class="modal-body"> 
          <img ng-src="{{selectedProductImage}}" style="max-width:100%;"> <!-- 加样式确保图片适配模态框 -->
        </div> 
      </div> 
    </div> 
  </div> 
</div>

另外,我还顺便修正了HTML里的{{category.categoryName[1]}},改成了{{categories[1].categoryName}}——原来的写法会取当前分类名称的第二个字符,而不是第二个分类的名称,这应该是你不小心写错的地方~

内容的提问来源于stack exchange,提问作者M Dube

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:24:46