1
我有一個封裝了websocket連接的AngularJS工廠。我想有一些這些在我的每個連接到不同的終端控制器使用(由下面personId
指定)如何將參數傳遞給AngularJS工廠?
angular.module('personService', ['ngResource']).
factory('Person', function($resource) {
var service = {};
if (service.ws) { return; }
var personId = ??? // This will be different for each person.
var ws = new WebSocket("ws://127.0.0.1:5000/" + personId + "/");
ws.onopen = function() {
console.log("WebSocket opened");
};
ws.onerror = function(err) {
console.log("WebSocket error " + err);
}
ws.onmessage = function(message) {
service.callback(message.data);
};
service.ws = ws;
service.send = function(message) {
service.ws.send(message);
}
service.subscribe = function(callback) {
service.callback = callback;
}
return service;
});
function Ctrl($scope, $timeout, Person) {
$scope.p1 = Person("personId1"); // ??
$scope.p2 = Person("personId1"); // ??
}
這不起作用。因爲第二次調用init會覆蓋原始的ws。 – nickponline
'ws'作爲'Person'構造函數的私有變量,不會被覆蓋。當然。 – lib3d