Shuvro Shuvro - 1 month ago 13
Javascript Question

Angularjs ng-view not showing data

I am learning Angularjs from Tuts+ Easier JavaScript Apps with AngularJS tutorial. Now I am at the part where they discussed Routing Primer using ng-view. I am trying to show the list page contents in ng-view of index page. For some reason nothing is shown when I load index.html. I found from searching that From angular 1.2.0, ngRoute has been moved to its own module. I have to load it separately and declare the dependency. But still I can't show anything from my list page.

index.html

<!doctype html>
<html ng-app="myApp">
<head>
<title>Angular App</title>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="Ctrl">
<div ng-view></div>
</div>
</body>
</html>


list.html

<h3>List</h3>
<ul>
<li ng-repeat="contact in contacts">
<a href="#">{{contact.name}}</a>: {{contact.number}}
</li>
</ul>


app.js

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

app.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'list.html',
controller: 'Ctrl'
});
});

app.controller('Ctrl', function($scope){
$scope.contacts = [
{ name: 'Shuvro', number: '1234' },
{ name: 'Ashif', number: '4321' },
{ name: 'Anik', number: '2314' }
];
});

Answer

Remove the ng-controller from the div like this:

<body>
<div >
  <div ng-view></div>
</div>
</body>

To void "miss-routings" add the otherwise to the main configuration like: otherwise({ redirectTo: '/'});

app.config(function($routeProvider) {
        $routeProvider.when('/', {
            templateUrl: 'list.html',
            controller: 'Ctrl'
        }).otherwise({ redirectTo: '/'});
});

Online Demo

Comments