0

I have problem with controller load when I triggered ng-route. This is my main page:

    <!DOCTYPE html>
    <html>
    <head ng-app="testapp">
        <script type="text/javascript" src="angular.js"></script>
        <script type="text/javascript" src="angular-route.js"></script>
<script type="text/javascript" src="app.js"></script>
            <title>XX</title>
    </head>
    <body>
        <nav ng-controller="defaultnav"></nav>
        <div ng-view></div>
    </body>
    </html>

and this is my app.js file:

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

app.config(function ($routeProvider) {
            $routeProvider.
                when("/", {
                    templateUrl: "index.html"
                })
                .when("/page1", {
                    templateUrl: "page1.html"
                })
        })

inside the page1.html I inisiate controller like this:

<div ng-controller="page1">

</div>

<script type="text/javascript">
    app.controller('page1', function ($scope) {
        // code...
    })
</script>

I don't know best practice to handle this. When I code this I got error with [Error, ctrlreg] it says that I have problem about registering controller. Please give me advice to solve this. Thanks in advance.

imma hanitya
  • 33
  • 1
  • 9

1 Answers1

1
  1. In JS, the app name in line var app = angular.module('enterprise', ['ngRoute']); is enterprise
  2. In HTML, <head ng-app="testapp">, the app name is testapp. Change to <head ng-app="enterprise">
  3. Its best practice to load the java script seperately. so remove js code from html and keep it in seperate file and load it

Click here for working demo in plnkr.

You can use AngularJS ngRoute:

// create the module and name it scotchApp
var scotchApp = angular.module('scotchApp', ['ngRoute']);

// configure our routes
scotchApp.config(function($routeProvider) {
  $routeProvider

  // route for the home page
    .when('/home', {
    templateUrl: 'pages/home.html',
    controller: 'mainController'
  })

  // route for the about page
  .when('/about', {
    templateUrl: 'pages/about.html',
    controller: 'aboutController'
  })

  // route for the contact page
  .when('/contact', {
    templateUrl: 'pages/contact.html',
    controller: 'contactController'
  })

  //otherwise redirect to home
  .otherwise({
    redirectTo: "/home"
  });
});

// create the controller and inject Angular's $scope
scotchApp.controller('mainController', function($scope) {
  // create a message to display in our view
  $scope.message = 'Everyone come and see how good I look!!!!';
});

scotchApp.controller('aboutController', function($scope) {
  $scope.message = 'Look! I am an about page.';
});

scotchApp.controller('contactController', function($scope) {
  $scope.message = 'Contact us!.';
});
Nishanth
  • 825
  • 6
  • 18