maydawn maydawn - 3 months ago 8
Javascript Question

$scope object remains undefined after $http.get

I have an object that returns after

$http.get
. I'm trying to use this object to display in a
clientdetails.html
template page.

var app = angular.module('openlegacy', ['ngRoute']);

app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'pages/main.html',
controller : 'clientCtrl'
})

.when('/new', {
templateUrl : 'pages/clientform.html',
controller : 'postController'
})

.when('/client/:clientid', {
templateUrl : 'pages/clientdetails.html',
controller : 'clientCtrl'
})
});

app.controller('clientCtrl', function($scope, $http, $location) {
$scope.oneclient = {};
$scope.getClient = function(clientid) {
$http({
method : 'GET',
url : '/openlegacy/web/client/' + clientid,
headers : {'Content-Type': 'application/json'}
})
.then(function(response) {
$scope.oneclient = response.data;
// console.log($scope.oneclient);
$location.path('/client/' + clientid);
});
};


Here the console.log shows the JSON response object exactly how I want it.

In the
clientdetails.html
I have
<div class="container" ng-controller="clientCtrl">
with a simple
<h1>{{oneclient.name}}</h1>
.

I always get an error that
oneclient
is undefined.

Why is that object undefined ?

The same approach worked perfectly in a
clientlist.html
when I used an
$http.get
to get the list of all clients.

Answer

You need to run the method when the controller is instantiated. To run a method onload of the controller, you could use NgInit
ng-init="yourfunction()"
(Read comments to the main question for more info)

Be aware that NgInit can add some unnecessary logic into the scope. A cleaner way to call a method whenever the controller is instantiated is to call the method from inside of the controller:

$scope.yourfunction();