angularjsangular-ui-routerangular-controller

Assigning separate controller files in AngularJS's UI Router


I am new to AngularJS and AngularJS's UI Router. I have a basic index.html file in which I inject the views. And then I have app.js with the routes inside, a template client.html and a controller about that template called clientContoller.js I am trying to figure out how to assign to the controller of the $stateProvider.state the controller file clientController.js like for example in the code below.

$stateProvider.state('client', {
    url: '/client',
    templateUrl: 'client.html',
    controller: 'clientController.js',
    controllerAs: 'client'
});

Solution

  • What you are supposed to assign to the controller key for ui-router is the name of the controller (not the filename). You then simply need to include your clientController.js file in your index.html. For example:

    Inside index.html:

    <script src="clientController.js"></script>
    

    Inside your clientController.js:

    angular.module('myApp', [])
        .controller('ClientCtrl', function($scope){
            // controller code
        });
    

    Inside your app.js state definition:

    .state('client', {
        url: '/client',
        templateUrl: 'client.html',
        controller: 'ClientCtrl'
    });