0

creating service

myApp.factory('serviceHttp', ['$http', function(http) {
  http.get($scope.url).then(function(result){
    serviceVariable = result;
  }
  return serviceVariable;
}

Controller

function appController($scope, serviceHttp){
  $scope.varX = serviceHttp;
  if(serviceHttp){
    // decision X;
  } else {
    // decision Y;
  }
}

view:

input(ng-if='varX') serviceHttp Exist
input(ng-if='!varX') serviceHttp noExist

The above code always shows varX not exist because app installs during http call of service. I want to use angular service to inject variables from server to make decision at time of booting the application.

2
  • var is an invalid variable name in javascript. Commented Nov 24, 2013 at 12:20
  • thats not the issue. edited. Commented Nov 24, 2013 at 12:22

2 Answers 2

2

Try to rewrite factory by this way that returns promise:

myApp.factory('serviceHttp', ['$http', function(http) {

   var factory = {
       query: function () {
          var data = http.get($scope.url).then(function(result){
              return result;
           },
          function (result) {
            alert("Error: No data returned");
         });
           return data;
       } 
   }
   return factory;  
}]);

From controller:

serviceHttp.query().then(function (result) {
    $scope.varX =  = result;                            
}

Here is Demo Fiddle

in demo we used other URL source

Sign up to request clarification or add additional context in comments.

Comments

2

If i correct understand you, you should doing it like this:

 var app = angular.module('YourModule', []);
    app.factory("serviceHttp", function($http) {
        var serviceHttp={};

        serviceHttp.yourGetRequest = function(yourUrl) {

           return $http.get(yourUrl);
       };

        return serviceHttp;
    });

And for example, controller:

        var Controller = function($scope,serviceHttp) {
        $scope.varX='';
        $scope.loading = true;
      var returnArr = serviceHttp.yourGetRequest($scope.url).success(function(dataFromServer) {
$scope.loading = false;
$scope.varX = dataFromServer;
})

};

in view you can use ng-show, like this:

<div ng-show="loading" class="loading"><img src="../styles/ajax-loader-large.gif"></div>

When your application start loading, $scope.loading = true and this div shown, and when you get response from server $scope.loading became false and div doesn't show.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.