gpt4 book ai didi

javascript - 使用for循环构建数组的 Angular

转载 作者:行者123 更新时间:2023-11-29 21:46:55 26 4
gpt4 key购买 nike

我正在测试 Angular 应用程序中动态构建数组。基本上我有一个作用域函数,它生成一组人并返回该数组,我在该数组上有一个 ng-repeat。该数组没有显示,但我也没有在控制台中收到任何错误,所以我知道发生了什么:

我是否正确调用了 getPerson 函数?如果有更好的方法,请告诉我。

heres the fiddle as well

$scope.person = {
firstname: "",
lastname: "",
isActive: true,
fullname: function() {
var personobject;
personobject = $scope.person;
return personobject.firstname
+ " "
+ personobject.lastname;
}
};

$scope.people = function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
};
$scope.getPerson = function(first, last, active) {
var newPerson = $scope.person;
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};

最佳答案

我在这里更新了你的 fiddle :https://jsfiddle.net/7j2khgbj/2/

var myapp = angular.module("myapp", []);
myapp.controller('appCont', function($scope) {

var Person = function(){
this.firstname = "";
this.lastname = "";
this.isActive = true;

};

Person.prototype.fullname = function() {
return this.firstname
+ " "
+ this.lastname;
};

var getPerson = function(first, last, active) {
var newPerson = new Person();
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};

$scope.addPerson = function() {
$scope.people.push({
firstname: $scope.person.firstname,
lastname: $scope.person.lastname
});
$scope.person.firstname = '';
$scope.person.lastname = '';

};

$scope.people = (function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
})();


/*$scope.people = [
{firstname: 'abdul', lastname: 'ahmad'},
{firstname: 'mahmud', lastname: 'samrai'},
{firstname: 'gasser', lastname: 'badawi'},
{firstname: 'ibtihaj', lastname: 'jasim'},
{firstname: 'abudi', lastname: 'ahmad'},
{firstname: 'ahmad', lastname: 'jasim'},
{firstname: 'abdul', lastname: 'samrai'}
];*/
});

我看到的一些问题:

1) $scope.people 是一个函数,不是一个数组(所以我简单地执行了它并保存了结果)

2) 你总是覆盖这个人(你需要一个为数组元素创建新实例的 Person 类,而不是用新数据覆盖同一个实例 - 这样你会在所有数组元素中得到相同的东西)

3) 在 $scope 上,你应该放置需要从 View 中访问的东西。辅助函数可以只在 Controller 中本地化(如果您不希望它们作为服务,尽管作为服务它们是可重用的)

4) 在 ng-repeat 上跟踪(在重复键的情况下)

关于javascript - 使用for循环构建数组的 Angular ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30813486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com