我正在尝试使用 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/