0

I'm writing a simple AngularJS script to load data from a socket.io event and then add it to the ng template, this is my JS:

// Socket.io logic:
var messages = [];
socket.on("chat message", function(message){
    messages.push(message); //message = {username: String, text: String}
});

// AngularJS logic:
var app = angular.module("chat", []);
app.controller("MessagesCtrl", function ($scope) {
    $scope.messages = messages;    
})

Now I'd like to understand how to update my ng template when a new message is added to my messages[]...

This is an example fiddle with one attempt: http://jsfiddle.net/v8v67ohn/1/
As you can see, clicking the button nothing happens...

What am I doing wrong?

2 Answers 2

1

Use ng-click instead of setting a new MessagesCtrl in a jQuery event handler.

You can do this like this:

JS:

var app = angular.module('myApp', []);

app.controller('MessagesCtrl', function ($scope) {
    $scope.messages = [{username: "foo", text: "hi"}, {username: "bar",text: "hey"}, {username: "foo",text: "LOL"}]    

    $scope.onClick = function() {
        $scope.messages = [{username: "foo", text: "hi"}, {username: "bar",text: "hey"}, {username: "foo",text: "LOL"}, {username: "new one", text: "Hi all, I'm new here"}]
    };
});

HTML:

<body ng-app="myApp" ng-controller="MessagesCtrl">
    <script type="text/ng-template" id="message.html">
        <b>{{message.username}}</b>: {{message.text}}
    </script>        
    <div>
        <div ng-repeat="message in messages" ng-include="'message.html'">
        </div>
    </div>
    <button id="click" ng-click="onClick()">aaaa</button>
</body>

See the jsfiddle-demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! What if I wan to call "onClick" on the socket.io event?
You have to notify angularjs that you changed the messages array. Therefore put the socket code block in your controller and make an $apply call like this: $scope.$apply(function() { $scope.messages.push(message); }); More information about $apply: sitepoint.com/understanding-angulars-apply-digest
1

Use on button click ng-click="newData()" function

<button id="click" ng-click="newData()">aaaa</button>

And Set in your controler

$scope.newData=function(){


 $scope.messages = [{username: "foo", text: "hi"}, {username: "bar",text: "hey"}, {username: "foo",text: "LOL"}, {username: "new one", text: "Hi all, I'm new here"}]
}

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.