0

I created one service that contains some values and I populate it and imported in two controllers.
Problem is that first controller see all data in it.
But second controller see just empty values.
As service is singleton it should be visible in both.
Am I doing something wrong here?

app.service("MyModel", ['$filter', function ($filter) {
    this.items = [];
}]);
app.controller('FirstController', ['$scope', 'MyModel', function ($scope, MyModel) {
    var vm = this;
    vm.MyModel = MyModel;
}]);
app.controller('SecondController', ['$scope', 'MyModel', function ($scope, MyModel) {
    var vm = this;
    vm.MyModel = MyModel; // empty (like a new instance)
}]);
1110
  • 7,829
  • 55
  • 176
  • 334

1 Answers1

0

First of all, in your code itself you are initializing this.items = []; And in both controller u are assigning service reference (vm.MyModel = MyModel;). Here your Service having one empty array that is assigned to vm.MyModel.

For example: DO this

app.controller('FirstController', ['$scope', 'MyModel', function ($scope, MyModel) {
    var vm = this;
    MyModel.items = [1,2 3, 4];
}]);
app.controller('SecondController', ['$scope', 'MyModel', function ($scope, MyModel) {
    var vm = this;
    console.log(MyModel.items); \\ it will print array [1, 2, 3, 4]
}]);

In Singleton design pattern only one object is created and same is shared for all who ask for it. Here in this case when you inject the SERVICE to any controller, reference of that SERVICE is passed to that controller. So if there is any change in SERVICE object from any of the controller,it will reflect in other controller too.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Raj Rj
  • 3,497
  • 4
  • 24
  • 34