Search code examples
angularjsangularjs-scope

Angular $scope object not getting assigned


I'm trying to assign an object through a service to a $scope object. However I get an error saying that the object is undefined. I'm making an asynchronous call to get the object and below I've used $timeout service to simulate the same. I've tried $q.defer() and returned a promise suspecting it to be a timing issue and also called $apply() to invoke binding but nothing seems to be working. Below is the link to the code in plunker. Pls help me out with this. http://plnkr.co/edit/wyF4Bx1a39IEWS3m8Loe?p=info

<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="[email protected]" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="profctrl">
  <p>Hello {{usr}}!</p>
</body>

</html>

var ub = angular.module('app', []);
ub.controller('profctrl', ["$scope", "formsub", "$log", "$timeout", function($scope, formsub, $log, $timeout) {
  $log.log("In Profile controller");
  $scope.msg = "";
  $scope.usr = {};

  var fbresponse = {
    name: 'xyz',
    email: '[email protected]'
  };

  $scope.usr = formsub.getprof(fbresponse);
  $timeout(function() {
    $log.log('$scope.usr', $scope.usr);
  }, 2000);
}]);

ub.service('formsub', ["$http", "$log", "$q", "$timeout", function($http, $log, $q, $timeout) {
  var user = {};
  var self = this;

  self.msg = "";


  self.getprof = function(user) {

      $timeout(function() {
        $log.log('user assigned');
        return user;
      }, 2000);

    } //getprof

}]);

Solution

  • var ub = angular.module('myApp', []);
    ub.controller('profctrl', ["$scope", "formsub", "$log", "$timeout", function($scope, formsub, $log, $timeout) {
    $log.log("In Profile controller");
    $scope.msg = "";
    $scope.usr = {};
    
    var fbresponse = {
    name: 'xyz',
    email: '[email protected]'
    };
    formsub.getprof(fbresponse).then(function(result) {
    $scope.usr = result;
    alert(JSON.stringfy(result));
    });
    
    }]);
    
    ub.service('formsub', ["$http", "$log", "$q", "$timeout", function($http, $log, $q, $timeout) {
     var user = {};
     var self = this;
     self.msg = "";
     self.getprof = function(user) {
      var deferral = $q.defer();
      $timeout(function() {
        $log.log('user assigned');
        deferral.resolve(user);
      }, 2000);
      return deferral.promise;
    } //getprof
    }]);
    

    Demo

    I have use the $q.I think this will help you