javascript - how to read a variable inside service in angularjs? -
i want know how can value of variable inside service, have following code:
mymodule.service('notify', ['$window', function(win) { var msgs = []; // want read variable this.message = function(msg) { msgs.push(msg); if (msgs.length == 3) { win.alert(msgs.join("\n")); msgs = []; } }; }]); and want read msgs variable controller.
declaring variables var makes them local scope of function. if want expose can store on object itself.
mymodule.service('notify', ['$window', function(win) { this.msgs = []; // want read variable this.message = function(msg) { this.msgs.push(msg); if (this.msgs.length == 3) { win.alert(this.msgs.join("\n")); this.msgs = []; } }; }]); then can retrieve msgs on service reading
service.msgs a better pattern create getter method retrieve messages.
mymodule.service('notify', ['$window', function(win) { var msgs = []; // want read variable this.getmessages = function () { return msgs; }; this.message = function(msg) { msgs.push(msg); if (msgs.length == 3) { win.alert(msgs.join("\n")); msgs = []; } }; }]); then can retrieve messages calling
service.getmessages();
Comments
Post a Comment