Jorge Rodríguez Jorge Rodríguez - 4 months ago 13
AngularJS Question

Angular js - Not able to push to an array

I'm trying to push some info to an array and show it with ng-repeat but for some reason it's not working

This is my 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 = {};
}


}

})();


Here's the plunkr: https://plnkr.co/edit/jPOJDXoG1vgNfsDzyJAD?p=preview

Thanks for the help

Answer

for your controller you are using a controller As syntax so you will have to refer to scope variables with a prefix of 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>

Also in your controller you have to initialize a newComment object

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

Comments