Reputation: 14835
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?
Upvotes: 0
Views: 120
Reputation: 2023
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"}]
}
Upvotes: 1
Reputation: 4360
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
Upvotes: 1