David Eriksen
David Eriksen

Reputation: 21

Angular.js routing not working

Angular is working as I can see the {{ text }} but I can't seem to get the ng-view to display.

My code is:

index.html:

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <script src="https://code.angularjs.org/1.3.5/angular.js"></script>
    <script src="https://code.angularjs.org/1.3.5/angular-route.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  <body ng-app='app'>
    <div class="main_container" ng-controller="MainController">
    <span ng-cloak>{{text}}</span>
    <div ng-view></div>
    </div>

    <!-- modules -->
    <script src='app.js'></script>
    <!-- controllers -->
    <script src='MainController.js'></script>
    <script src='home.js'></script>     
  </body>
</html>

home.js:

app.controller('home', function($scope) {
    $scope.words = 'It works!';
});

MainController:

app.controller('MainController',function($scope){
    $scope.text = 'Hello World!';
});

home.html:

<div ng-controller="home">
    <h3>{{ words }}</h3>
</div>

app.js:

var app = angular.module('app', ['ngRoute']);
app.config(function($routeProvider, $locationProvider){
    $routeProvider.
        when('/index',{
            templateUrl: 'home.html',
            controller: 'home'
        }).
        otherwise({
            redirectTo: '/index' 
        });
     //$locationProvider.html5Mode(true);
});

edit: It seems to work in plunker but when I open the file in chrome I get the following error:

"XMLHttpRequest cannot load {{file location}}. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."

Upvotes: 2

Views: 1104

Answers (2)

hartz89
hartz89

Reputation: 669

You don't need the ng-controller attribute on your root element in home.html because you are already defining the controller for that template when you set up your $routeProvider. Beyond that your code looks good. If you really want to get ahead of the game, though, I would recommend using UI Router if you plan to do any advanced routing in your application. It is much more robust and easier to work with than Angular's ngRoute, widely used, and well-documented.

Upvotes: 1

Alhuck
Alhuck

Reputation: 1029

Your Code is working fine !! there may be problem on which file to load first so please take care of the order of the files added in your HTML

Here is the working plunker with your code. here ng-view loads with no problem

http://embed.plnkr.co/oNADizOltrGitbWTWNXf/preview

Hope this helps!!!

Upvotes: 0

Related Questions