chat application
VC: chat.html
<!DOCTYPE html>
<html ng-app="chatApp">
<head>
<meta charset="UTF-8">
<title>AngularJS Chat</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<style>
body {
font-family: 'Segoe UI', sans-serif;
background: #f4f6f8;
margin: 0;
padding: 20px;
display: flex;
justify-content: center;
}
.container {
width: 400px;
background: #fff;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
padding: 20px;
}
h2 {
margin-top: 0;
text-align: center;
color: #333;
}
#chat {
border: 1px solid #ddd;
border-radius: 4px;
padding: 10px;
height: 250px;
overflow-y: auto;
background: #fafafa;
margin-bottom: 10px;
}
.msg {
margin: 6px 0;
padding: 6px 10px;
border-radius: 4px;
background: #e1f5fe;
color: #333;
position: relative;
}
.msg strong {
color: #0277bd;
}
.timestamp {
font-size: 10px;
color: #777;
position: absolute;
right: 8px;
bottom: 4px;
}
input[type="text"] {
width: calc(100% - 80px);
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
margin-right: 5px;
}
button {
padding: 8px 12px;
background: #0288d1;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background: #0277bd;
}
</style>
</head>
<body ng-controller="ChatController">
<div class="container">
<h2>💬 AngularJS Chat</h2>
<div id="chat">
<div class="msg" ng-repeat="m
in messages track by $index">
<strong>{{m.sender}}:</strong>
{{m.text}}
<div class="timestamp">{{m.time}}</div>
</div>
</div>
<div style="display: flex;">
<input type="text" ng-model="message"
ng-keypress="($event.which === 13) && send()" placeholder="Type
a message..." />
<button ng-click="send()">Send</button>
</div>
</div>
<script>
angular.module('chatApp', [])
.controller('ChatController', ['$scope',
'$timeout', function($scope, $timeout) {
$scope.messages = [];
$scope.message = '';
const ws = new WebSocket('ws://localhost:8080');
ws.onmessage = function(event) {
const data = JSON.parse(event.data);
$scope.$apply(() => {
$scope.messages.push({
sender: data.sender
|| 'Server',
text: data.text,
time: new Date().toLocaleTimeString()
});
scrollToBottom();
});
};
$scope.send = function() {
if ($scope.message.trim())
{
const msg = {
sender: 'You',
text: $scope.message,
time: new Date().toLocaleTimeString()
};
ws.send(JSON.stringify(msg));
$scope.messages.push(msg);
$scope.message = '';
scrollToBottom();
}
};
function scrollToBottom() {
$timeout(() => {
const chat = document.getElementById('chat');
chat.scrollTop = chat.scrollHeight;
}, 100);
}
}]);
</script>
</body>
</html>
Comments
Post a Comment