gpt4 book ai didi

javascript - 如何使用 AngularJS 将对象插入数组

转载 作者:IT王子 更新时间:2023-10-29 03:18:45 25 4
gpt4 key购买 nike

我正在尝试使用 Angular 推送功能,但它不起作用。

我想将字符串(或对象)添加到数组中。

我在 Stack Overflow 上搜索了基本示例,但找不到。

任何人都可以更正我的代码或编写一个非常基本的示例吗?

这是我的例子。

这是 HTML 代码:

<form ng-controller="TestController as testCtrl ng-submit="testCtrl.addText(myText)">
<input type="text" value="Lets go">
<button type="button">Add</button>
</form>

这是 Java 脚本代码:

(function() {
var app = angular.module('test', []);

app.controller('TestController', function() {
this.arrayText = {
text1: 'Hello',
text2: 'world',
}

this.addText = function(text) {
arrayText.push(this.text);
}
});
})();

最佳答案

推送仅适用于 array 。

将您的 arrayText 对象设为数组对象。

像这样尝试

JS

this.arrayText = [{
text1: 'Hello',
text2: 'world',
}];

this.addText = function(text) {
this.arrayText.push(text);
}
this.form = {
text1: '',
text2: ''
};

HTML

<div ng-controller="TestController as testCtrl">
<form ng-submit="addText(form)">
<input type="text" ng-model="form.text1" value="Lets go">
<input type="text" ng-model="form.text2" value="Lets go again">
<input type="submit" value="add">
</form>
</div>

关于javascript - 如何使用 AngularJS 将对象插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30484653/

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