2

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

1
  • you really should include all the relevant code in the question body. In particular, the HTML. In the current plunker you linked, the JavaScript is using the controller as syntax, and you declared your ng-controller this way, ng-controller="Article as vm", but the data bound items are using $scope syntax (i.e., they are not referring to vm at all).
    – Claies
    CommentedJul 22, 2016 at 22:45

2 Answers 2

2

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

1
  • Thanks @eltonKamami, you're right, I missed the controller as syntaxCommentedJul 22, 2016 at 22:57
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> 

Here is the updated plunkr https://plnkr.co/edit/HK4WIYCF6poMXncBU9Uk?p=preview

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.