Zulhilmi Zainudin Zulhilmi Zainudin - 4 months ago 43
Javascript Question

AngularJS: UI Router doesn't load the inline template and controller

This is my first time using UI Router inside AngularJS project. I have a problem where when I click a link to view a post, it doesn't show up.

The post template is not showing and I'm still at the home page. I can see the URL flashing like

http://localhost:8000/#/posts/1
and attempt to change, but, it goes back to
http://localhost:8000/#/home
.

Plunker: http://plnkr.co/edit/KV6lwzKUHrIZgVWVdrzt

What I am missing here?

Note 1: I already read UI Router documentation and I think I'm not missing anything.

Note 2: I'm following this tutorial (thinkster).

Note 3: I'm using SimpleHTTPServer
python -m SimpleHTTPServer 8000
command to serve this project.

This is my app.js:

app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider){

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

$urlRouterProvider.otherwise('home');

}]);

...

app.controller("PostsCtrl", ["$scope", "$stateParams", "postsFactory", function($scope, $stateParams, postsFactory){

// grab the right post from postsFactory posts array
$scope.post = postsFactory.posts[$stateParams.id];
console.log($scope.post);
}]);


And this is my index.html:

<ui-view></ui-view>

...

<script type="text/ng-template" id="/posts.html">
<div class="page-header">
<h3>
<a ng-show="post.link" href="{{post.link}}">
{{post.title}}
</a>
<span ng-hide="post.link">
{{post.title}}
</span>
</h3>
</div>
</script>

Answer

Issue in your code is in your router config for posts state. It should be like below. URL should be /posts/:id instead of posts/:id.

 $stateProvider
        .state('posts', {
            url: '/posts/:id',
            templateUrl: '/posts.html',
            controller: 'PostsCtrl'
        });