Roby Sottini Roby Sottini - 4 months ago 35
AngularJS Question

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.

Can anyone correct my code or write a very basic example?

Here is my example.

This is the HTML code:

<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:

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

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

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

Answer

Push only work for array .

Make your arrayText object to Array Object.

Try Like this

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>