Angular js - 无法推送到阵列

时间:2016-07-22 22:35:37

标签: javascript angularjs

我试图将一些信息推送到数组并使用ng-repeat显示但由于某种原因它无法正常工作

这是我的控制者:

(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 = {};
    }


}

})();

这里是傻瓜:https://plnkr.co/edit/jPOJDXoG1vgNfsDzyJAD?p=preview

感谢您的帮助

2 个答案:

答案 0 :(得分:2)

对于您的控制器,您使用的是控制器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>

同样在你的控制器中你必须初始化一个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 = {};
    }


}

Updated Plunker

答案 1 :(得分:0)

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

这是更新的plunkr https://plnkr.co/edit/HK4WIYCF6poMXncBU9Uk?p=preview