Reputation: 3068
Binding a service/factory variable within a controller works perfectly unless the factory variable is initiated through $http. Can anyone explain why?
NOTE: Since controller.someVariable = factory.someVariable doesn't work. Currently I am referencing the factory variable directly for manipulation as factory.someVariable
Controller:
app.controller('SecondCtrl',function($scope,testFactory){
$scope.obj = testFactory.obj;
$scope.factory = testFactory;
$scope.jsonData = testFactory.jsonData; //Not Binding
//Accessing $scope.factory.jsonData works while $scope.jsonData doesn't
});
Factory:
app.factory('testFactory', ['$rootScope','$http',function ($rootScope,$http) {
var factory = {};
factory.obj = { 'name':'Jhon Doe'};
factory.jsonData;
factory.fromjson = function() {
$http.get("data.json")
.success(function(data){
factory.jsonData = data.result;
})
}
factory.fromjson();
return factory;
}]);
Plunker: http://plnkr.co/edit/wdmR5sGfED0jEyOtcsFz?p=preview
Upvotes: 0
Views: 53
Reputation: 22323
As I've mentioned in the comments, the reason this is occurring is because $scope.jsonData = testFactory.jsonData;
is a value assignment, and unfortunately that value isn't available from the server yet when this assignment occurs. the other assignments work because they are reference assignments.
One quick but dirty way to solve this would be to declare factory.jsonData = {};
instead of factory.jsonData;
. This would change the call to a reference assignment (object to object) and allow changes to one to propagate to the other.
Upvotes: 1