Manually changing the URL does not call the controller in AngularJS

时间:2016-07-11 21:50:40

标签: angularjs angular-ui-router

I have a application with main pages as app.html and my controller is app.js. The following is the code in app.js:

angular.module(constants.MODULE_NAME).controller('AppCtrl', function ($scope, $state, $log, $http) {

    $scope.role = '';

    $http.get("htttp://localhost:8082/service/getUserRole")
        .then(function (response) {
            $scope.role = response.data.context;
            debugger;
            if ($scope.role.toLowerCase() == "hr") {
                //direct view to hr dashboard
                $state.go("app.hr");
            } else if($scope.context.toLowerCase() == "eemployee"){
                //direct view to employee dashboard
                $state.go("app.employee");
            }
            else{
                //do nothing
                $state.go("app");
            }});
});

So when I run this website the controller is called and based on the value of role the respective dashboard is displayed.When the website runs it hits http://localhost:9080/#/ which is calling the above controller and redirects too http://localhost:9080/#/hr/dashboard (or) http://localhost:9080/#/employee/dashboard.

I have the following in my router.js

export default ['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider) => {
  $stateProvider

    .state('app', {
      url: '/',
      template: require('./app.html'),
      controller: 'AppCtrl',
      controllerAs: 'app'
    })

    .state('app.hr', {
      url: 'hr/dashboard',
      template: require('./hr/dashboard/index.html'),
      controller: 'HRCtrl',
      controllerAs: 'hrctrl'
    })
    .state('app.employee', {
      url: 'employee/dashboard',
      template: require('./employee/dashboard/index.html'),
      controller: 'EMPCtrl',
      controllerAs: 'empctrl'
    });


  $urlRouterProvider.otherwise('/');
}];

Now when I change the URL to http://localhost:9080/#/ and hit enter then the controller is not getting called. But when I do a refresh the controller gets called. Can I know how I can fix this issue.

0 个答案:

没有答案