markhamknight markhamknight - 7 days ago 6
AngularJS Question

AngularJS $state.go looses data between controllers and not showing in the template

I am simply getting information from my API, and it responds well.

console.log(response)
will output,

Object {id: 1, username: "testmd", first_name: "Juan",
last_name: "Dela Cruz", type: "Pediatrician"…}


Controller

vm.getDoctor = function(id) {
$http.get(CONSTANTS.LINK+'/doctors/'+id).success(function(response) {
vm.thisDoctor = {
name : response.first_name + ' ' + response.last_name,
address : response.clinical_address,
};
console.log(vm.thisDoctor.address);
$state.go('tabs.doctor');
});
}


Now I am accessing vm.thisDoctor in my view doctors-this.html

<a class="item item-thumbnail-left">
<img src="cover.jpg">
<h2>{{ appt.thisDoctor.name }}</h2>
<p>{{appt.thisDoctor.address}}</p>
</a>


Here's my
app.js


.state('tabs.doctor', {
url: '/doctor/{doctorId}',
views: {
'tab-appts': {
templateUrl: 'templates/appts/doctors-this.html',
controller: 'ApptsCtrl as appt'
}
}
})


Is my
code
wrong? I've been working this for hours now.

Answer

After getting the response from the server, you are changing the view with $state.go thats why you are loosing the data. Instead, you can pass the object to the state and assign it to the controller scope back as below.

JS1

vm.getDoctor = function(id) {
        $http.get(CONSTANTS.LINK+'/doctors/'+id).success(function(response) {
            vm.thisDoctor = {
                name : response.first_name + ' ' + response.last_name,
                address : response.clinical_address,
            };
            console.log(vm.thisDoctor.address);
            $state.go('tabs.doctor', {
                args: {
                    data: vm.thisDoctor
                }
            });
        });
    }

JS2

.state('tabs.doctor', {
        url: '/doctor/{doctorId}',
        views: {
          'tab-appts': {
            templateUrl: 'templates/appts/doctors-this.html',
            controller: 'ApptsCtrl as appt' 
          }
        },
        params: { args: {} }    // Need to add this
    })

ApptsCtrl (inject $stateParams)

vm.thisDoctor = ($stateParams.args || {}).data;
Comments