
JS
使用 Angular.JS 中的 ng-repeat 指令,我们可以在 HTML 页面中循环遍历一个集合,并将集合中的每个元素渲染为相应的 HTML 元素。ng-repeat 还允许我们根据特定条件检查来选择性地使用另一个集合。在本文中,我们将探讨如何使用 ng-repeat 来检查条件并根据结果使用不同的集合。
在 ng-repeat 中,我们可以使用 ng-if 指令来检查条件是否为真。如果条件为真,则使用原始集合进行渲染;如果条件为假,则使用另一个集合进行渲染。这为我们提供了一种灵活的方式来动态选择要渲染的数据。让我们来看一个简单的示例。假设我们有两个集合:students 和 teachers。我们希望根据用户的角色来决定要显示的集合。如果用户是学生,则显示学生集合;如果用户是教师,则显示教师集合。以下是一个基本的示例代码:html<div ng-app="myApp" ng-controller="myCtrl"> <h2>学生</h2> <ul> <li ng-repeat="student in students" ng-if="userRole === 'student'">{{student.name}}</li> </ul> <h2>教师</h2> <ul> <li ng-repeat="teacher in teachers" ng-if="userRole === 'teacher'">{{teacher.name}}</li> </ul></div><script>var app = angular.module('myApp', []);app.controller('myCtrl', function($scope) { $scope.students = [ {name: '小明'}, {name: '小红'}, {name: '小刚'} ]; $scope.teachers = [ {name: '张老师'}, {name: '李老师'}, {name: '王老师'} ]; $scope.userRole = 'student'; // 设置用户角色为学生});</script>在上面的示例中,我们使用 ng-repeat 指令在两个不同的 Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号