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
$httpis async, you need to return the promise, you are trying to return immediately the data even if it hasn't come back from the server yet. because these are both primitives, and not objects, they aren't "bound" to each other, you are trying to assign the value of one to the value of the other.factoryobject, in the second case, you are accessing a primitive on$scope.$scope.jsonDatacan only receive the value that is present ontestFactory.jsonDataat the time of assignment. If these were objects, then they would be a reference assignment instead. This is not an angular issue, but a javascript assignment issue.