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); } }); })();
Approach: In this approach, the push() method is used to insert the element at the end of the array. In the first example, a static value 'Geek' is inserted in the array and in the second example a input box is provided to the user to push the value they want.
The push() method is a built-in method in AngularJS that inserts an object into an existing array. It takes two arguments: the object to push and the index of the position to insert the object. The first argument is the object that will be pushed into the array and should be of type string, number, boolean, or null.
'Push' is for arrays. You can do something like this: app.js: (function() { var app = angular. module('myApp', []); app. controller('myController', ['$scope', function($scope) { $scope.
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>
Please check this - http://plnkr.co/edit/5Sx4k8tbWaO1qsdMEWYI?p=preview
Controller-
var app= angular.module('app', []); app.controller('TestController', function($scope) { this.arrayText = [{text:'Hello',},{text: 'world'}]; this.addText = function(text) { if(text) { var obj = { text: text }; this.arrayText.push(obj); this.myText = ''; console.log(this.arrayText); } } });
HTML
<form ng-controller="TestController as testCtrl" ng-submit="testCtrl.addText(testCtrl.myText)"> <input type="text" ng-model="testCtrl.myText" value="Lets go"> <button type="submit">Add</button> <div ng-repeat="item in testCtrl.arrayText"> <span>{{item}}</span> </div> </form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With