我正在编写一个简单的AngularJS脚本来从socket.io事件加载数据,然后将其添加到ng模板中,这是我的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;
})
现在,我想了解如何在我的消息[]中添加新消息时更新我的ng模板...
这是一个尝试的例子:http://jsfiddle.net/v8v67ohn/1/
如您所见,单击按钮没有任何反应......
我做错了什么?
答案 0 :(得分:1)
使用ng-click
而不是在jQuery事件处理程序中设置新的MessagesCtrl。
你可以这样做:
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>
答案 1 :(得分:1)
使用按钮点击ng-click =&#34; newData()&#34;功能
<button id="click" ng-click="newData()">aaaa</button>
并设置在你的控制器中
$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"}]
}