使用getter和setter这应该相对简单,但我不确定如何正确设置getter和setter。
功能是这样的:
服务:
app.factory('chatbox',['$http',function($http){
var total_chats = 0;
var registeredChats = [];
var registerChat = function(userid) {
//Places Chat into variable
};
var getChat = function(userid) {
//Gets Chat for the Controller
};
var killChat = function(userid) {
//Gets Chat from Variable
};
}]);
我希望能够从包含该服务的任何控制器将数据存储到此服务中吗?
答案 0 :(得分:0)
您需要将您的功能定义为服务成员。因此,不是var
而是this.
this.registerChat = function(userid) {
//Places Chat into variable
};
this.getChat = function(userid) {
//Gets Chat for the Controller
};
this.killChat = function(userid) {
//Gets Chat from Variable
};
然后您就可以在控制器中使用chatbox
angular.controller('Controller1', function($scope, chatbox){
$scope.kill = function(userId, chat){
chatbox.killChat(userId, chat);
}
})
答案 1 :(得分:0)
我就是这样做的:
app.service('chatbox',['$http',function($http){
var service = {
getChats : getChats,
setChats : setChats
};
return service;
var total_chats = 0;
var registeredChats = [];
function getChats(){
//Insert logic here
}
function setChats(){
// Insert logic here
}
}]);
答案 2 :(得分:0)
试试这个:
app.factory('chatbox',['$http',function($http){
var total_chats = 0;
var registeredChats = [];
var registerChat = function(userid) {
//Places Chat into variable
registerChat.push(userId);
total_chats = total_chats + 1;
};
var getChat = function(userid) {
//Gets Chat for the Controller
return registered_chats;
};
var killChat = function(userid) {
//Gets Chat from Variable
... you get the idea
};
var toReturn = {
getChat: getChat,
registerChat: registerChat,
killChat: killChat
};
return toReturn
}]);