0

I am trying to fetch data from server and assign them to array in sharedScope factory. Next I want to simply inject factory into my two separated controllers and use two-way data binding between them to operate on the same array.

The similar approach I want to achieve is very well described here: https://stackoverflow.com/a/24913983/5195524

Data field has already been assigned and everything works fine. The problem starts when i want to fetch data from server first. What should I do to make the data immediately available in controllers?

Community
  • 1
  • 1
T. Love
  • 3
  • 1
  • can you share plnkr or show what have you done? – JanisP Aug 05 '15 at 21:09
  • Please show us what you have tried and where you are stuck. – Madness Aug 05 '15 at 21:12
  • @JanisP I tried this: http://pastebin.com/pwMqEbyN Response comes after a call controllers and it didn't work. How can I fix that and make data immediately available in controllers? Should I change my approach? – T. Love Aug 05 '15 at 21:27
  • I changed a bit your approach... is this something close to what you wanted to achieve? http://plnkr.co/edit/VkmOTMoIxXy19uCfjmW8?p=preview – JanisP Aug 05 '15 at 22:22
  • @JanisP It is exactly what I want! Thanks a lot! – T. Love Aug 05 '15 at 22:29

1 Answers1

1

Your version is not working because of javascript variable scopes. Instead of accessing prototype chain you are creating new variable in success function. The most easiest fix is:

app.factory("sharedScope", function($http) {
            var self = this;
            self.data = {};

            init();

            function init() {
                    $http.get('http://jsonplaceholder.typicode.com/posts').
                    success(function(response) {
                            self.data.text = response;
                    });
            }

            return self;
    });

Here is working plnkr http://plnkr.co/edit/6gA7nt4cYwOWJGAuoLe5?p=preview

JanisP
  • 1,233
  • 15
  • 16