简体   繁体   中英

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 ?

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);

});

You can read like this, this will contain the object. Also object does not have an index.

you have to just use $scope.AnswerScheme

 Console.log($scope.AnswerScheme);

if its an array you can just use $scope.AnswerScheme[0]

 Console.log($scope.AnswerScheme[0]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM