maydawn maydawn - 1 month ago 4
Javascript Question

$scope object remains undefined after $http.get

I have an object that returns after

. I'm trying to use this object to display in a
template page.

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

app.config(function ($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) {
method : 'GET',
url : '/openlegacy/web/client/' + clientid,
headers : {'Content-Type': 'application/json'}
.then(function(response) {
$scope.oneclient =;
// console.log($scope.oneclient);
$location.path('/client/' + clientid);

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

In the
I have
<div class="container" ng-controller="clientCtrl">
with a simple

I always get an error that
is undefined.

Why is that object undefined ?

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


You need to run the method when the controller is instantiated. To run a method onload of the controller, you could use NgInit
(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: