D
D
Dmitry Ivanov2017-05-31 12:27:59
JavaScript
Dmitry Ivanov, 2017-05-31 12:27:59

Why is the link not established by reference with the object from the factory in the controller?

I am writing an application in AngularJS. I have a controller (in a simplified form)

app.controller("orgsItemCtrl", function($scope, orgsItemService) {
  $scope.data	= orgsItemService.data;
  $scope.fn		= orgsItemService.fn;
}

and a factory to it (also given in a simplified form)
app.factory('orgsItemService', function($http) {
  var serviceObj	= {
    data	: {},
    fn	: {
      init	: function() {
        // Тут получаем данные с сервера через $http и сохраняем их в serviceObj.data
      }
    }
  };

  serviceObj.fn.init();
  return serviceObj;
}

In the view, I establish a connection with the fields of the data object from orgsItemCtrl .
As a result, it does not work as intended, because. data in orgsItemCtrl remains an empty object, even after receiving data from the server.
If we transfer the functionality from the factory to the controller, then everything works. Working code example:
app.controller("orgsItemCtrl", function($scope, orgsItemService) {
  $scope.data	= {};
  $scope.fn		= {
    init	: function() {
      // Тут получаем данные с сервера через $http и сохраняем их в serviceObj.data
    }
  }
}

So why isn't linking by reference happening at this point:$scope.data = orgsItemService.data;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2017-05-31
@IDma88

I missed the most important point in the assignment, how you change the data upon receipt, if you do not modify the existing data object but replace it with a new one, then it is quite logical that the controller does not see the replacement.
In addition, read this www.codelord.net/2016/11/23/spotting-outdated-angu...
You call orgsItemService and try to make a factory, in addition, you give an object in the factory and not a class instance

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question