Search code examples
angularjsember.jsangular-ui-routerember-router

What is the equivalent of the emberJS routing beforeModel function just for angularJS


With emberJS I can intercept a state/route activation process with:

http://emberjs.com/guides/routing/redirection/#toc_before-the-model-is-known

overriding the beforeModel function.

What is the equivalent of the emberJS beforeModel routing function just for the ui router module in angularJS ?

I am missing this very important functionality in angularjs.

This question is a subsequent question to this:

Can I use a pre-computed value as url parameter in emberjs


Solution

  • After checking some sites I have come up with a working solution for my case:

      $rootScope.$on('$stateChangeStart', function(ev, toState, toParams, fromState, fromParams) {
            if (toState.name === "projects.selected.dates.day") {
    
              ev.preventDefault();
    
              var currentDate = new Date();
              var currentYear = currentDate.getFullYear();
              var currentMonth = currentDate.getMonth() + 1;
              var currentDay = currentDate.getDate();
    
              // The first time the user opens a project the date data is null in the toParams
              if (!toParams.year && !toParams.month && !toParams.day) {
                toParams.year = currentYear;
                toParams.month = currentMonth;
                toParams.day = currentDay;
              }
    
              $state.go(toState.name, toParams, {
                notify: false
              }).then(function() {
                $rootScope.$broadcast('$stateChangeSuccess', toState, toParams, fromState, fromParams);
              });
            }
          });
    
    // Do the 'same' for the week state and month state...
    

    The above code works fine.

    I just do not like that the change/interception of a route happens not at the place where the state is added that means in the .config() function instead I have to intercept the states in the .run() function.

    I would have appreciated a stateChange function like this:

      .state('projects.selected.dates.day', {
            stateChange: function(stateData)
            {
               // hook in here to calculate url parameter
            },
            url: '/day/:year-:month-:day',
            views: {
              'planner@projects.selected.dates': {
                templateUrl: 'dateplanner.day.html',
                controller: 'DateplannerDayController'
              }
            }
          })