Akhilesh Chobey Akhilesh Chobey - 4 years ago 93
Javascript Question

AngularJS Routing to different page with different controller

I have two HTML pages. One is the

exam.html
and other is
result.html
. On certain condition in the controller
ExamCtrl
of exam.html, I route to
result.html
using
$location.path
. But however, on the
result
page, the controller
ResultCtrl
doesn't seem to load though I have added it in the config file.

angular config file:

angular.module('exam').config(['$stateProvider',
function ($stateProvider) {
// Exam state routing
$stateProvider
.state('exam', {
abstract: true,
url: '/exam',
template: '<ui-view/>'
})
.state('exam.list', {
url: '',
templateUrl: 'modules/exam/client/views/exam.client.view.html',
controller: 'ExamCtrl'
})
.state('/result', {
url: '/result',
templateUrl: 'modules/exam/client/views/exam-result.client.view.html',
contoller: 'ResultCtrl'
});
}
]);


ExamCtrl:

angular
.module('exam')
.controller('ExamCtrl', ['$scope', '$stateParams', '$location', 'Authentication', '$http',
function ($scope, $stateParams, $location, Authentication, $http) {


$scope.submitAnswer = function (selected) {
//some code
if (qtnCounter > 5) {
// loads the result page.
$location.path('/result');
} else {
$scope.getQues();
}
};
}
]);


ResultCtrl:

angular
.module('exam')
.controller('ResultCtrl', ['$scope', '$stateParams', '$location', 'Authentication', '$http',
function ($scope, $stateParams, $location, Authentication, $http) {

console.log('ResultCtrl');

}
]);


result.html:

<body ng-controller="ResultCtrl">
<h1>Result page!</h1>
</body>

Answer Source

Insted of using $location use the $state to change to a given state in your app.

Inject the $state in the controller and then call the transitionTo() which will load the view and setup the controller

angular
.module('exam')
.controller('ExamCtrl', ['$scope', '$state', 'Authentication', '$http',
  function ($scope, $state, Authentication, $http) {


$scope.submitAnswer = function (selected) {         
      //some code
      if (qtnCounter > 5) {
        // loads the result page.
        $state.transitionTo('/result');
      } else {
        $scope.getQues();
      }
    };
  }
]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download