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

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -