I want to know how can I get the value of a variable that is inside a service, I have the following code:
myModule.service('notify', ['$window', function(win) {
var msgs = []; // I want to read this variable
this.message = function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);
and I want to read the msgs variable from a controller.
Declaring variables with var makes them local to the scope of the function. If you want to expose it you can store it on the object itself.
myModule.service('notify', ['$window', function(win) {
this.msgs = []; // I want to read this variable
this.message = function(msg) {
this.msgs.push(msg);
if (this.msgs.length == 3) {
win.alert(this.msgs.join("\n"));
this.msgs = [];
}
};
}]);
Then you can retrieve msgs on your service by reading
service.msgs
A better pattern would be to create a getter method to retrieve the messages.
myModule.service('notify', ['$window', function(win) {
var msgs = []; // I want to read this variable
this.getMessages = function () {
return msgs;
};
this.message = function(msg) {
msgs.push(msg);
if (msgs.length == 3) {
win.alert(msgs.join("\n"));
msgs = [];
}
};
}]);
Then you can retrieve your messages by calling
service.getMessages();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With