Question

I have some navigation buttons on an Angular wizard-style webapp. For cosmetic reasons they need to be removed from each partial and added to the root "index.html":

<!-- Global navigation buttons for all partials -->
<div class="navbar navbar-fixed-top">
    <button class="btn btn-default" back-action>Back</button>
    <button class="btn btn-default" next-action>Next</button>
</div>

<div class="container ng-view ng-cloak">
     <!-- Partials rendered in here, managed by $routeProvider-->
</div>

I've attempted to isolate this logic using directives and scope variables to bind the click event and apply target destinations for each partial:

.directive('nextAction', ['$location', function($location) {
    return {
        restrict: 'A',
        link: function(scope, elm) {
            elm.on('click', function () {
               var nextUrl = scope.nextUrl;
               $location.url(nextUrl);
            });
        }
    };
}])

The URL's are then defined in each controller:

.controller('FirstStepCtrl', ['$scope', function ($scope) {
        $scope.backUrl = '/';
        $scope.nextUrl = '/first/second';
        ...

The problem is that scope.nextUrl is undefined since the directive scope does not inherit the controller scope.

Along with the fact it doesn't currently work, this approach also seems a bit fragile to me since it relies on navigation logic embedded in the controller code.

How might I create better global back/next buttons that dynamically redirect based on the current "page"?

Was it helpful?

Solution

Use a state manager to handle the back and next urls. Relieve the controllers of this responsibility. Then inject it into the directives that handle the back and next buttons.

.factory('stateMgr', ['$rootScope', function ($rootScope) {
    var stateMgr = {
        backUrl: '',
        nextUrl: ''
    };

    $rootScope.$on('$routeChangeSuccess', function (nextRoute, lastRoute) {
        // logic in here will look at nextRoute and then set back and next urls
        // based on new route   
        // e.g. stateMgr.backUrl = '/'; stateMgr.nextUrl = '/whatever';
    });

    return stateMgr;
}]);

then

.controller('FirstStepCtrl', ['$scope', function ($scope) {
    // do not need to do anything with back/next urls in here
    ...

and

.directive('nextAction', ['$location', 'stateMgr', function($location, stateMgr) {
    return {
        restrict: 'A',
        link: function(scope, elm) {
            elm.on('click', function () {
                $location.url(stateMgr.nextUrl);
            });
        }
    };
}])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top