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?

share|improve this question

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>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.