jmls
jmls

Reputation: 2969

ui-router, routes and splitting code into smaller fragments

I'm wanting to set up the routes in my app in the .config function. So I have this, which works well

(function() {

angular
    .module('myApp', ['ui.router'])
    .config(config)

config.$inject = ['$stateProvider','$urlRouterProvider'];

function config($stateProvider,$urlRouterProvider) {

    $urlRouterProvider.otherwise('/dashboard');

    $stateProvider
        .state('dashboard', {
            url: '/dashboard',
            templateUrl: 'partials/dashboard.html',
            controller: function($scope, $stateParams) { .. },
            controllerAs: 'dashboard
    })
  }

})();

however, I also trying to follow best practices as documented in https://github.com/johnpapa/angularjs-styleguide.

so, now my code read like this

[snip]
    templateUrl: 'partials/dashboard.html',
    controller: myController,
    controllerAs: 'dashboard'
   })
  }

 myController.$inject = ['$scope', '$stateParams']

 function myController($scope, $stateParams) { ... }
})();

this also works.

However, when there is a large number of routes, this file can get quite big and messy, so I tried to split the controller definitions into another file.

Angular now barfs with the error

Failed to instantiate module myApp due to: ReferenceError: myController is not defined

How would I go about fixing this ? Or am I completely mad and barking up the wrong tree - should I be declaring the routes somewhere else apart from in the module ?

thanks!

Upvotes: 0

Views: 839

Answers (1)

iH8
iH8

Reputation: 28668

Are you sure you added the controller to your application module and loading your resources in the correct order? This should work:

index.html:

<!DOCTYPE html>
<html ng-app="app">
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.min.js"></script>
        <script src="//rawgit.com/angular-ui/ui-router/0.2.13/release/angular-ui-router.js"></script>
        <script src="app.js"></script>
        <script src="controllers.js"></script>
    </head>
    <body ui-view></body>
</html>

app.js:

angular.module('app', [
    'ui.router'
]);

angular.module('app').config([
    '$stateProvider',
    '$urlRouterProvider',
    function ($stateProvider, $urlRouterProvider) {
        $urlRouterProvider.otherwise('/');
        $stateProvider.state('root', {
            'url': '/',
            'controller': 'rootController',
            'templateUrl': 'root.html'
        });
    }
]);

controllers.js:

angular.module('app').controller('rootController', [
    '$scope',
    function ($scope) {
        $scope.value = 'Foo';
    }
]);

root.html:

<h1>{{value}}</h1>

Here's a working example on Plunker: http://plnkr.co/edit/TnXkm3ukAWjyNqX463Js?p=preview

Upvotes: 1

Related Questions