mrcatmann
mrcatmann

Reputation: 51

AngularJS 1 - ng-repeat not re-rendering after array push

I'm trying to make a simpliest chat app in Angular 1.

Controller code:

app.controller('mainCtrl', function ($scope, $rootScope, $routeParams, $location, $http) {
    $scope.messages=[{'name':'user','text':'test'}];
    $scope.submitMessage = function () {
    $scope.messages.push({'name':'newuser','text':$scope.mymessage});
}
});

Template:

<div class="page-content" ng-controller="mainCtrl" ng-init="init()">
<div class="messages">
<p class="chat-message" ng-repeat="message in messages"><span class="username">{{message.name}}: </span>{{message.text}}</p>
</div>
<div style="clear:both"></div>
<form ng-submit="submitMessage()" ng-controller="mainCtrl">
    <input type="text" ng-model="mymessage" class="message-input" ></input>
</form>

When trying to console.log the $scope.messages array, it shows the new values, but the list itself does not change at all. What can be the reason?

Upvotes: 0

Views: 290

Answers (1)

Robin-Hoodie
Robin-Hoodie

Reputation: 4974

You've got ng-controller="mainCtrl" defined twice, this will actually instantiate 2 different instances of the controller, so the messages you push will be on the array in the second instance of your controller while you're repeating over the messages that are on the first instance of your controller.

You only need it on the surrounding div, everything that is nested inside this tag will be able to access the $scope on your controller.

<div class="page-content" ng-controller="mainCtrl" ng-init="init()">
  <div class="messages">
    <p class="chat-message" ng-repeat="message in messages"><span class="username">{{message.name}}: </span>{{message.text}}</p>
  </div>
  <div style="clear:both"></div>
  <form ng-submit="submitMessage()">
    <input type="text" ng-model="mymessage" class="message-input"/>
  </form>
</div>

Upvotes: 2

Related Questions