HoosierCoder HoosierCoder - 2 months ago 11
AngularJS Question

Angular.js basic routing

I have been following the tutorial:

https://thinkster.io/angular-rails#angular-routing

I have not done any rails integration yet, the question is specifically to angular.

When I do the hello worlds from the MainCtrl without using the router, everything works. When I use the router, I cannot get the inline angular template to display in my html page. Where is the error here?

app.js:

angular.module('flapperNews', ['ui.router'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {

$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
});

$urlRouterProvider.otherwise('home');
}])

angular.module('flapperNews', [])
.controller('MainCtrl', [
'$scope',
function($scope){
$scope.test = 'Hello world';
}]);


index.html:

<html>

<head>
<title>My Angular App</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.19/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
<script src="app.js"></script>
</head>

<body ng-app="flapperNews">

<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view> <!-- this is supposed to display the template below but it shows nothing -->
</div>
</div>

<script type="text/ng-template" id="/home.html">
<div class="page-header">
<h1>Flapper News</h1>
</div>
</script>
</body>

</html>

Answer

Your controller is recreating the module instead of referencing it. Change it like so:

angular.module('flapperNews')
.controller('MainCtrl', [
'$scope',
function($scope){
  $scope.test = 'Hello world';
}]);
Comments