0

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?

0

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.