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

标签 javascript arrays angularjs function

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

相关文章:

javascript - 随机访客看到图像

javascript - .toLocaleString() 不在带小数的数字上显示逗号

javascript - 使用 Javascript 循环将 Leaflet GeoJSON 层从 GeoServer 添加到数组

Java:数组大小的插入排序问题

javascript - 以表格格式打印二维数组

javascript - 错误 : JSON. 解析:来自 Json 的 JSON 数据的第 1 行第 1 列出现意外字符

javascript - 用 Protractor 点击复选框?

javascript - 为什么 XMLHttpRequest 实例只能发送一个请求?

javascript - AngularJS:包装指令并传递属性

angularjs:从服务返回json数据到 Controller