jribeiro
jribeiro

Reputation: 3463

Angular UI Router replace view on runtime

I'm trying to change a parent view template on runtime - inside a service.

My app config looks like:

$stateProvider
.state('base', {
    abstract: true,
    views: {
        'header':       {
            controller: 'HeaderCtrl',
            templateUrl: 'header.html'
        },
        '': {
            template: '<div ui-view="main"></div>'
        }
    }
})
.state('base.home', {
    url: '/',
    views: {
        'main': {
            controller: 'SomeContentCtrl',
            templateUrl: 'content.html'
        }
    }
});

I then have a service which is called from SomeContentCtrl that will listen for an event and upon such event I want to set the templateUrl for the header to null. Something like:

angular
    .module('RemoveTemplate', [ ])
    .factory('RemoveTemplate', ['$window', '$view', '$state',
        function RemoveTemplate ( $window, $view, $state ) {

            var windowElem  = angular.element($window);

            var listen   = function ( ) {
                windowElem.on('RemoveTemplate', function ( event ) {
                    $view.load('header@base', {
                        templateUrl: null
                    });

                    // Trying both, even tried without refreshing the state
                    $state.reload();
                    $state.go('wh.lobby');
                });
            };

            return {
                listen:  listen
            };

        }
    ]);
});

But this isn't working at all. Have anyone came across a similar use case before?

Thanks

Upvotes: 1

Views: 1206

Answers (2)

LookForAngular
LookForAngular

Reputation: 1070

If you want to 'hide' the header section without removing the html try to use a ng-show directive inside the header tag and check the actual state.

<div ng-show="state.is('base')">

This way you only need to inject the $state service in the controller. When the state is base the div will show, if you navigate to child states it will hide.

p.s. $state.is returns a boolean, this method works with ng-if as well.

Upvotes: 0

Rodik
Rodik

Reputation: 4092

You can specify a templateURL function that runs each time you navigate to the state.

https://github.com/angular-ui/ui-router/wiki/Quick-Reference#template-templateurl-templateprovider

this method can check if it should supply a url or something else; example:

$stateProvider.state('home', {
        url: '/',
        templateUrl: function () {
            if (header === true) {
                return 'app/templates/home.html';
            } else {
                return somethingElse;
            }
        }
    })

Upvotes: 3

Related Questions