I have a json object that come from node server as a variable "msg" and receive it by socket.on
and I want to use this json with angularjs as ng-repeat
please help !
<script>
var socket = io();
socket.on('chat message', function(msg){
$("ul").html(msg);
var app = angular.module('myApp', []);
app.controller('jsCtrl', function($scope) {
$scope.msgs = msg;
});
});
</script>
<ul>
<li ng-repeat="item in msgs">
{{item.Name}}
</li>
</ul>
i have in server this code var
initData = JSON.parse('<%-JSON.stringify(data)%>');
and I think I must use json.stringify(msg); to convert it to json
how can I use it with angular js ng-repeat !
Maybe,
(function() {
angular.module('myApp', [])
.controller("jsCtrl", jsCtrl);
jsCtrl.$inject = ['$scope'];
function jsCtrl($scope) {
var socket = io();
socket.on('chat message', function(msg) {
$scope.msgs = angular.fromJson(msg);
}
}
});
})();
It's just an idea, I don't know exactly what kind of data is coming.
Related
I'm implementing a payment gateway into my SPA built with angularjs.
The problem is that this payment gateway requires you to include a script with a id of the payment.
this is my current setup....
(note the controller just runs some server-side script, it returns all information about the payment I just need to get the id)
Here is my controller:
(function (){
var PaymentGateController = function ($scope, $rootScope, $state, paymentFactory, $sce) {
$scope.ready = false;
paymentFactory.getResult()
.then(function (result) {
$scope.ready = true;
$scope.url = result.data.id;
}, function(error) {
console.log(error);
});
}
PaymentGateController.$inject = ['$scope', '$rootScope','$state', 'paymentFactory', '$sce'];
angular.module('hcbcApp.paymentGate', []).controller('PaymentGateController', PaymentGateController);
}());
.. and here is my view:
<div ng-if="ready">
<form action="https://peachpayments.docs.oppwa.com/tutorials/integration-guide#" class="paymentWidgets">VISA MASTER AMEX</form>
<script type="text/javascript" src="https://test.oppwa.com/v1/paymentWidgets.js?checkoutId={{url}}"></script>
</div>
don't think you can do that, scripts are loaded first before the bootstrapping stage takes place in angular. Look for lazy loading solution. This post seems to fit what you want to do:
Single page application - load js file dynamically based on partial view
This feels really dirty but it works so I'm going with it...
Added this to my controller:
$scope.makeScript = function (url) {
var script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', 'text/javascript');
document.getElementById('paymentDiv').appendChild(script);
};
and then to this when I get the url
$scope.url = "https://test.oppwa.com/v1/paymentWidgets.js?checkoutId=" + result.data.id;
$scope.makeScript($scope.url);
I am using node.js, express, jade and socket.io, I can get javascript code to run on the jade side, but I can't generate html coming from the script. block
I had to update my question based your input. Here are the files:
server.js
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: res}); // res is the reponse object
socket.on('my other event', function (res) {
console.log("socket.io connected and data sent to jade");
});
});
layout.jade:
doctype html
html
head
title= title
script(src='components/jquery/dist/jquery.min.js')
script(type='text/javascript' src='https://cdn.socket.io/socket.io-1.0.6.js')
script(type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jade/1.11.0/jade.min.js')
script(type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jade/1.11.0/runtime.min.js')
script.
var socket = io.connect('http://localhost:8898/');
socket.on('news', function (data) {
var photo = data.hello.data[0].images.original.url;
});
body
block content
img(src="#{photo}") // <--- issue here, creates "undefined" image
index.jade:
extends layout.jade
img(src="#{photo}") // my problem is here, creating <undefined> tags in html
You could remove the existing component content, and then re-render using jQuery in the jQuery AJAX callback. Something like..
jade:
label#data
After:
script.
var socket = io.connect('http://localhost:8898/');
socket.on('news', function (data) {
$('#data').text('');
$('#data').text(data);
});
Might be a little too obvious but from that example, but I think the JS block inside the script tag needs to be indented. Haven't been able to test that though
script.
var socket = io.connect('http://localhost:8898/');
socket.on('news', function (data) {
console.log("socket.io.on data reaching jade");
console.log(data); // prints fine, but to console only.
socket.emit('my other event', { my: data });
});
Since you are extending from layout.jade and index.jade is your child-template. Don't you need to declare that the html is your block content? Like this:
extends layout
block content
#{data} // my problem is here, creating <undefined> tags in html
p #{data.stuff}
img(src="images/bird.jpg") // works
I am creating a service to get the values saved as "FirstName" in a Row "name", when save is ok i have the values in the database, but when i try to get this values i have something like this:
people:
-
All the values in the list empty but i don't know why this happen if it is a problem in the controller or in the service.
<script src="https://www.parsecdn.com/js/parse-1.3.2.min.js"></script>
<div ng-app="app">
<ul ng-controller="MyCtrl">
people
<li ng-repeat="person in people">{{person}}</li>
</ul>
</div>
<script type="text/javascript">
Parse.initialize("key", "key");
var People = Parse.Object.extend("People");
var peoples= new People();
peoples.set("name", "FirstName");
peoples.save(null),{
success:function(peoples){
peoples.save();
}
}
var app = angular.module('app', []);
app.controller("MyCtrl", ["$scope", "PeopleService", function($scope, PeopleService){
$scope.people = PeopleService.getPeople();
}]);
app.service("PeopleService", function($q){
var people = null;
return {
getPeople: function(){
var deferred = $q.defer();
people = [];
var queryObject = new Parse.Query(People);
queryObject.find({
success: function (results) {
for (var i = 0; i < results.length; i++) {
var result = results[i];
people.push(result.get("name"));
}
deferred.resolve(people);
},
error: function (error) {
deferred.reject(error);
}
});
return deferred.promise;
}
}
});
</script>
You should set the $scope.people value from the success callback function of parse.com call.
Code
app.controller("MyCtrl", ["$scope", "PeopleService", function($scope, PeopleService){
PeopleService.getPeople().then(function(data){ //success fn
$scope.people = data
},function(data){ //error fn
$scope.people = data
});
}]);
This question has already been answered, but I can't understand it at all. You can find it at this link.
socket.on calls its callback too many times
I have the same problem as this fellow. I'm attempting to make a chat program with socket.io, but when more than one user joins, each message outputs the number of times of how many users have been connected.
For example, when one user is connected, and he submits a message. It outputs once. When two users are connected, each of their messages output twice.
When three users are connected, each of their messages output three times.
Here is my client side code:
$('document').ready(function() {
var server = io.connect('http://localhost:8888');
$('.chat').keydown(function(event){
var save = this;
if(event.which == 13){
server.emit('message', $(save).val());
$(save).val('');
return false;
}
});
server.on('incoming', function(message){
$('#textfield').append("<p>" + message + "</p>");
});
});
Here is my server side code:
var socket_io = require('socket.io').listen(8888).sockets;
socket_io.on('connection', function(socket){
socket.on('message', function(message){
socket_io.emit('incoming', message)
});
});
Thank you!
You can use socket.broadcast.emit() to send to everyone except that socket:
var io = require('socket.io')(8888);
io.on('connection', function(socket) {
socket.on('message', function(message) {
socket.broadcast.emit('incoming', message);
});
});
UPDATE: The following example works just fine for me:
server.js:
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function(socket) {
socket.on('message', function(message) {
socket.broadcast.emit('incoming', message);
});
});
index.html:
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$('document').ready(function() {
var server = io.connect('http://localhost');
$('.chat').keydown(function(event) {
if (event.which == 13) {
var $save = $(this);
server.emit('message', $save.val());
$save.val('');
return false;
}
});
server.on('incoming', function(message){
$('#textfield').append("<p>" + message + "</p>");
});
});
</script>
</head>
<body>
<input type="text" class="chat">
<div id="textfield"></div>
</body>
</html>
When pressing enter, the message in the input box is only displayed once to all other connected socket.io users.
Okay, I've finally figured out the problem.
I'm using Express 4.0. That means, I'm using routes to run the server, and I had the socket io code running inside the route. Each time a user connects, it has to go through the route first, and it's all binding onto the same socket_io.
Thanks to everybody who helped!
I also faced it, like multiple socket calls in network tab and i just add this "transports" key object to socket instance, both on client and backend.
socket = io("http://localhost:3002", {
transports: ['websocket']
})
React, Node, AWS EB
I want to send data via socket.io to my client via nodejs.
The data I am receiving are from pusher.
I am using an express backend and loading my server like that.
#!/usr/bin/env node
var debug = require('debug')('testApp');
var app = require('../app');
var Pusher = require('pusher-client');
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});
/**
* return pusher data
*/
var API_KEY = 'cb65d0a7a72cd94adf1f';
var pusher = new Pusher(API_KEY, {
encrypted: true
});
/**
* Socket.io
*/
var io = require("socket.io").listen(server, {log: true});
io.sockets.on("connection", function (socket) {
// This will run when a client is connected
// This is a listener to the signal "something"
socket.on("data", function (data) {
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function (data) {
console.log(data);
});
});
// This is a signal emitter called "something else"
socket.emit("something else", {hello: "Hello, you are connected"});
});
On my client I am running the following script:
index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js" />
<script src='/javascripts/socket.js'></script>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %> Juhu!</p>
</body>
</html>
My socket.js file:
var socket = io.connect(window.location.hostname);
socket.on('data', function(data) {
var total = data.total;
//print data to console
console.log(data);
});
My problem is that nothing gets shown in the console in my webbrowser, even though the data is coming in at my nodejs application.
Any recommendation what I am doing wrong?
I appreciate your replies!
I do believe the problem is when you use: socket.emit("something else", {hello: "Hello, you are connected"});
but have this in client-side: socket.on('data', function(data) {.
When you emit, you use the channel "something else", but on the client-side you are checking on the channel "data".
So on client-side you should be having socket.on('something else', function(data){.
Hope I helped. There isn't much info I could find on sockets.io, so I do not know if there is a preexisting channel called 'data'. Do enlighten me if so :)