如何使用AngularJS将对象推入数组 [英] How to push object into an array using AngularJS
本文介绍了如何使用AngularJS将对象推入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用角度推送功能,但它不起作用。
我想将字符串(或对象)添加到数组中。
我在Stack Overflow搜索了一些基本的例子,但是我找不到它。
任何人都可以更正我的代码或写一个非常基本的例子吗?
这是我的例子。
> 这是HTML代码:
$ b
< ; form ng-controller =TestController as testCtrl ng-submit =testCtrl.addText(myText)>
< input type =textvalue =Lets go>
<按钮类型=按钮>添加< /按钮>
< / form>
这是Java脚本代码:
(function(){
var app ='测试控制器',函数(){
this.arrayText = {
text1:'Hello ',
text2:'world',
}
this.addText = function(text){
arrayText.push(this.text);
}
});
})();
解决方案
只推送ar的工作ray $。
使您的 arrayText
对象为Array对象。
试试像这样
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 =textng-model =form.text1value =Lets go>
< input type =textng-model =form.text2value =让我们再去>
< input type =submitvalue =add>
< / form>
< / div>
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);
}
});
})();
解决方案
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>
这篇关于如何使用AngularJS将对象推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文