Reputation: 367
I am trying to display the data to my view but $scope.plan
outputs {}
. I am thinking that it would output the fetched data from the initGetEdit
function, console.log()
inside the $http.post
outputs expected data.
controller.js
var id = $stateParams.id;
$scope.plan = {}
$scope.initGetEdit = function(){
var data = { id : id }
$http.post("someUrl", data).then(function(res){
$scope.plan = res.data;
console.log($scope.plan); //----> logs expected data
})
}
$scope.initGetEdit();
console.log($scope.plan); //----> logs {}
In my view
I have something like this.
view
<input ng-model="plan.something" type="text" />
UPDATE
First thank you for those answers provided and the comments, appreciated it. It gives me an insight. I solved my issue by removing the initGetEdit
function and staying with just the http.post
.
Upvotes: 0
Views: 53
Reputation: 159
Try keeping the second console in watch.
$scope.$watch('plan',function(){
console.log($scope.plan);
});
Upvotes: 2
Reputation: 2134
At first, you declare a variable $scope.plan = {}
after that in http
call of your $scope.initGetEdit
function its empty object after the function http
is an async call your object may be filled based on the response. until that it will be an empty object.
@Ujjwala Bollam mention in answer to print it in the console.
var app = angular.module('testApp',[]);
app.controller('testCtrl',function($scope,$http){
//var id = $stateParams.id;
var id=1;
$scope.plan = {}
$scope.initGetEdit = function(){
var data = { id : id }
//$http.post("http://someurl", data).then(function(res){
$scope.plan ={id:1,something:"hai this is response data"};
console.log($scope.plan); //----> logs expected data
//})
}
$scope.initGetEdit();
console.log($scope.plan); //----> logs {}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div ng-app="testApp" ng-controller="testCtrl">
<input ng-model="plan.something" type="text" />
</div>
Upvotes: 1