Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

javascript - 如何使用AngularJS将对象推入数组(How to push object into an array using AngularJS)

I am trying to do use the angular push function but it is not working.(我试图使用角度推动功能,但它不起作用。)

I want to add strings (or objects) into an array.(我想将字符串(或对象)添加到数组中。)

I searched for basic examples here at Stack Overflow but I couldn't find it.(我在Stack Overflow上搜索了一些基本的例子,但我找不到它。)

Can anyone correct my code or write a very basic example?(谁能纠正我的代码或写一个非常基本的例子?)

Here is my example.(这是我的例子。)

This is the HTML code:(这是HTML代码:)

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

This is the Java Script code:(这是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);
        }
    });
})();
  ask by Roby Sottini translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Push only work for array .(仅推送数组工作。)

Make your arrayText object to Array Object.(将arrayText对象设为Array Object。)

Try Like this(试试这样)

JS(JS)

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

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

HTML(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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...