1

I have a controller for my navigation bar because it will be on some pages and not others. This is the markup for the navigation bar:

<html ng-app="myApp">
 <head>
   <title> My layout.html </title>
 </head>
 <body>
   <nav ng-controller="NavCtrl">
    I have this NAVBAR
   </nav>
  <div ui-view></div> 
 </body>
</html>

Normally, I would specify the name of my controller in my routes like this:

$stateProvider.state('/', {
 controller: 'NavbarCtrl'
});

But in this case, I don't have a route that corresponds to my nav bar, I just have my navbar controller file itself. My question is: how can I register the controller without a templateUrl via ui-router?

2
  • You just need to register a "NavCtrl" controller somewhere in your app, eg .controller('NavCtrl', function($scope) { .... }) Commented Jul 31, 2015 at 3:59
  • i don't need register also with stateProvider? interesting! Commented Jul 31, 2015 at 4:01

2 Answers 2

3

No need of registering the controller in ui-router; just define the controller on your app's module.

angular.module('myApp').controller('NavbarCtrl', function($scope) {
    $scope.testVar = "some value";
});

Now you can access testVar variable in part of the template that's managed by your controller.

Sign up to request clarification or add additional context in comments.

1 Comment

Very interesting! I didn't know that haha!
0

Another approach that I think provides a maintainable code is using a base state for your navbar in $stateProvider.

    $stateProvider
      .state('base', {
        templateUrl: 'base.html',
        controller: 'NavbarCtrl'
      })
      .state('base.child', {
        url: 'url-of-child-state',
        views: {
          'view-for-navbar': {
            templateUrl: 'child-template',
            controller: ChildCtrl
          }
        }
      })

Now you can use your navigation bar like a master page on various child pages. Just include code for your navigation bar in base.html and below that add this line <div ui-view="main-view"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.