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

Angular新手求助:ngFor用法及AngularJS相关代码修正

Hey there! Let's break this down clearly since you're coming from an AngularJS (Angular 1.x) background and mixing up concepts with newer Angular versions.

First, a critical point to remember: AngularJS (1.x) does NOT have the *ngFor directive — that's a feature of Angular 2+. In AngularJS, the equivalent loop directive is ng-repeat, which works perfectly with the $scope and controller patterns you already know.

Let's fix your code and make it work properly with AngularJS:

Corrected Full Code

<html ng-app="moduleA">
<head>
    <title> Collections </title>
    <script src="angular.js"></script>
    <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body ng-controller="CollectionController">
    <!-- Use AngularJS's ng-repeat instead of ngFor -->
    <div class="container">
        <h3>My Collection</h3>
        <ul class="list-group">
            <!-- ng-repeat iterates over the items array on $scope -->
            <li class="list-group-item" ng-repeat="item in items">
                {{ item.name }}: {{ item.details }}
            </li>
        </ul>
    </div>

    <script>
        // Define your module (just like you're used to in AngularJS)
        angular.module('moduleA', [])
        // Attach a controller to the module
        .controller('CollectionController', function($scope) {
            // Populate $scope with the data you want to loop through
            $scope.items = [
                { name: "Book", details: "A fantasy novel" },
                { name: "Laptop", details: "15-inch portable workstation" },
                { name: "Headphones", details: "Noise-canceling over-ear" }
            ];
        });
    </script>
</body>
</html>

Key Explanations for Your AngularJS Knowledge:

  • We use ng-controller="CollectionController" to link your controller to the DOM, so the $scope data becomes accessible in that part of the page.
  • ng-repeat="item in items" loops through the items array stored on $scope — each iteration creates a new <li> element and assigns the current array item to the item variable for interpolation.
  • The {{ item.name }} and {{ item.details }} syntax is the same interpolation you know from AngularJS, pulling values directly from $scope.

Just to recap: If you're working strictly with AngularJS (1.x), forget about *ngFor entirely — stick with ng-repeat paired with $scope and your existing module/controller workflow, and it'll work exactly how you expect.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:14:46