Imran Imran - 1 month ago 11
AngularJS Question

How to read object in angularjs controller?

I have no problems when I read an object in view. For example my code was:

angular.module('myApp',[])
.controller('myCtrl',function($scope){
var AnswerScheme = $scope.AnswerScheme = tbl_qst_master_answer.getByAnswerId(AnswerIdSelectedByStudent);
});


In my view:

{{AnswerScheme[0]}} // Then the output will be: {"myTestData":123}


However, I got problems if I want to read in the controller

AnswerScheme[0] // Then no results


How to read the object in
myCtrl
?

Answer

In your controller, you should use $scope to access the scope data, so, {{AnswerScheme[0]}} in view is equal to $scope.AnswerScheme[0] n controller

In your service you are returning an object instead of a promise.

If you return a promise, you can call a callback function.

Even though it gets displayed corectly in the view since the scope is always watched in the view.

As per our discussion if you add $timeout in controller you can access that object

The timeout loads the scope after sometime, and by that time the scope will get resolved.

angular.module('myApp',[])
.controller('myCtrl',function($scope,$timeout){
      var AnswerScheme = $scope.AnswerScheme = tbl_qst_master_answer.getByAnswerId(AnswerIdSelectedByStudent);

       $timeout(function () { 
           console.log($scope.AnswerScheme) 
       },900);

});
Comments