在AngularJS中,可以使用ng-repeat指令来迭代一个数组或对象的属性,并使用indexOf()函数来检查对象是否存在于数组中。
以下是一个示例代码:
HTML代码:
-
{{person.name}} - {{person.age}}
JavaScript代码:
// 创建一个AngularJS应用
var app = angular.module('myApp', []);
// 创建一个控制器
app.controller('myCtrl', function($scope) {
// 定义一个people数组
$scope.people = [
{name: 'John', age: 25},
{name: 'Jane', age: 30},
{name: 'Bob', age: 35}
];
// 检查对象是否存在于数组中
$scope.checkIfInArray = function(person) {
var index = $scope.people.indexOf(person);
if (index !== -1) {
console.log(person.name + ' exists in the array at index ' + index);
} else {
console.log(person.name + ' does not exist in the array');
}
};
// 调用函数检查对象是否存在于数组中
$scope.checkIfInArray({name: 'John', age: 25});
});
这个例子中,ng-repeat指令被用来迭代people数组,并显示每个person对象的name和age属性。
在控制器中,使用indexOf()函数来检查传入的person对象是否存在于people数组中。如果返回的索引不等于-1,则表示对象存在于数组中,否则表示对象不存在于数组中。
最后,调用checkIfInArray()函数来检查{name: 'John', age: 25}对象是否存在于数组中,并在控制台输出结果。