1

Can someone crate an example of how I could set a $scope variable from a outside the controller using a factory or service that uses AJAX?

Every time I have tried the AJAX variable returns undefined because the request has not returned yet, so $scope.var is undefined. After the AJAX request returns, $scope.var is still undefined even if I call the service from the Controller. Please help.

2
  • can you show us what you've tried so far? possible duplicate of stackoverflow.com/questions/22898927/… Commented Nov 5, 2014 at 18:51
  • Here is an example for you: stackoverflow.com/a/26657303/949476. Service method userService.getUsers returns promise. Then in controller you do something like this: userService.getUsers().then(function(users) { $scope.users = users; }); Commented Nov 5, 2014 at 18:54

1 Answer 1

1

Please see demo here http://plnkr.co/edit/JcRY8uHRYaHH33UTH7Bt?p=preview

var app = angular.module("myapp", []);

app.service("dataService", function($http, $q) {

  var data = [];

  function getData() {

    var deffered = $q.defer();
    var request = {
      url: 'data.json',
      method: 'GET'
    };
    $http(request).then(sucess, error);

    function sucess(response) {
      deffered.resolve(response.data);
    }
    function error() {
      deffered.reject();
    }

    return deffered.promise;

  }


  return {
    data: data,
    getData: getData
  }

})
app.controller('MyControl', function($scope, dataService) {

  $scope.data = [];
  dataService.getData().then(function(response) {

    $scope.data = response;
  })
});
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for taking your time in writing out all that code it did the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.