GetOffMyLawn
GetOffMyLawn

Reputation: 1452

ngRoute not working with external controller files

When I include my controllers in my app.js file, routing and controller functionality works fine. It looks something like this:

index.html

<!DOCTYPE html>
<html data-ng-app='ckbApp' >    
<head >
</head>

<body>
    <div class="container" >
        <div ng-include="'header.html'"></div>

        <div ng-view class="viewBody">
        </div>

        <div ng-include="'footer.html'"></div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular-route.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
    <script src="ckbApp.js"></script>

</body>

</html>

app.js

'use strict';

var app = angular.module('app', ['ngRoute']);

app.config(['$routeProvider',
    function($routeProvider) {
          $routeProvider. 
          when('/About', {
              templateUrl: 'Views/About.html',
              controller: 'controller'
          }). 
          when('/Blog', {
              templateUrl: 'Views/Blog.html',
              controller: 'controller'
          }).
          when('/FAQ', {
              templateUrl: 'Views/FAQ.html',
              controller: 'controller'
          }). 
          when('/Home', {
              templateUrl: 'Views/Home.html',
              controller: 'controller'
          }). 
          otherwise({
             redirectTo: '/Home' 
          });
}]);

app.controller('controller', ['$scope', '$http', function ($scope, $http) {
    $http.get('data.json').success(function(data) {
        $scope.data = data;
  });    
}]);

But when I try putting the controller into an external file, none of the routing works. I know the controller still works, because the scope.data still loads for 'header.html'. My external controller file looks something like this:

'use strict';
angular.module('app', []).controller('controller', ['$scope', '$http', function ($scope, $http) {
    $http.get('data.json').success(function(data) {
    });    
}]);

And I have the controller source included at the bottom of index.html

<script src="/Controllers/controller.js"></script>

I read somewhere that ngRoute requires a server to be running, but even with my server going, it doesn't work externally, but works with the controller included in app.js

Upvotes: 1

Views: 1698

Answers (1)

JB Nizet
JB Nizet

Reputation: 691893

angular.module('app', [])

That redefines the module named 'app'. You just want to get a reference to the existing module defined in the other JS file, and add a controller to it:

angular.module('app')

Upvotes: 5

Related Questions