我正在尝试将一些信息推送到数组并使用 ng-repeat 显示它,但由于某种原因它不起作用
这是我的 Controller :
(function () {
'use strict';
angular
.module('app.article')
.controller('Article', Article);
function Article($location) {
var vm = this;
vm.comments = [];
vm.addComment = addComment;
function addComment() {
vm.comments.push(vm.newComment);
vm.newComment = {};
}
}
})();
这是 plunkr:https://plnkr.co/edit/jPOJDXoG1vgNfsDzyJAD?p=preview
感谢您的帮助
最佳答案
对于您的 Controller ,您使用的是 Controller As 语法,因此您必须引用前缀为 vm
的范围变量。
<div ng-controller="Article as vm">
<form ng-submit="vm.addComment()">
<textarea placeholder="Sign in to share your thoughts." ng-model="vm.newComment.comment"></textarea>
<input type="text" class="form-control" ng-model="vm.newComment.user">
<input type="submit" class="btn btn-primary" value="Post">
</form>
<ul>
<li ng-repeat="comment in vm.comments">{{comment.user}} - {{comment.comment}}</li>
</ul>
</div>
此外,在您的 Controller 中,您必须初始化一个 newComment 对象
function Article($location) {
var vm = this;
vm.comments = [];
vm.addComment = addComment;
vm.newComment = {user: '', comment: ''}
function addComment() {
vm.comments.push(vm.newComment);
vm.newComment = {};
}
}
关于javascript - Angular js - 无法推送到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38536171/