I've create this piece of code:
app.controller('SiteDetailCtrl',function($scope, $routeParams, $http){
//remove ":" in SiteId
var SiteId = $routeParams.SiteId.replace(':','');
$scope.Site = $http.get('path-to-ajax/Site/'+SiteId);
.success(function(data){
$scope.Site = data;
console.log($scope.Site);
})
.error(function(){
$scope.Site = 'NULL';
alert('Ajax Fail');
});
console.log($scope.Site);
});
I don't understand why $scope.Site
is available in Success
function but outside ($http
) $scope.Site
is null
. Please explain for me what happen here.
I'm new to AngularJS
.
the success
handler function you define in line 6 will run way later than the console.log
statement from line 14. it is nothing angular specific but how asynchronous code works. i suggest you research a bit in that direction.
Console.log you are using outside is executed immediately when the controller is initialized,
So the $scope.Site is not have a value
but Success function is called after the data is returned from the server, so value is present in the Success function
I haven't tested it yet but apparently the fact that your're returning a value from $http $scope.Site = $http.get(... //its worng
and as Valerij said the nature of $http is ajax meaning asynchronous result, causes this bug.
you need to use it like this:
app.controller('SiteDetailCtrl',function($scope, $routeParams, $http){
//remove ":" in SiteId
var SiteId = $routeParams.SiteId.replace(':','');
$http.get('path-to-ajax/Site/'+SiteId);
.success(function(data){
$scope.Site = data;
console.log($scope.Site);
})
.error(function(){
$scope.Site = 'NULL';
alert('Ajax Fail');
});
// console.log($scope.Site);
});
html:
{{$scope.Site}} //this will work, asynchronously get results after Success function