I am trying to display content using Angular, angular UI-Router, and without relying on $scope.
In my mainController, I don't have any issues using directive likes ng-repeat. But I don't know how to access information from my postsController.
I know that I am pulling the correct data in my controller since console.log shows the correct post object. Now I just need to know how to access it.
index.html
<script type="text/ng-template" id="/posts.html" >
{{ }} // What do I put here?
</script>
app.js
app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
...
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'postsController'
});
$urlRouterProvider.otherwise('home');
}
]);
app.js
app.controller('postsController', [
'$stateParams',
'posts',
function($stateParams, posts) {
var vm = this;
vm.post = posts.posts[$stateParams.id];
console.log(vm.post);
}
]);
You state will be using controllerAs so you need to define controller as below. And by using alias of your controller you could show data on view.
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'postsController as postCtrl'
});
View
<script type="text/ng-template" id="/posts.html" >
<ul>
<li ng-repeat="p in postCtrl.post">{{p}}</li>
</ul>
</script>
You should have latest version like 0.2.0+ version of ui-router to declare controllerAs like I suggested, for older version you could use @RadimKöhler suggestion.
You should use declaration controllerAs:
.state('posts', {
url: '/posts/{id}',
templateUrl: '/posts.html',
controller: 'postsController',
controllerAs: 'vm' // this will be injected into $scope
});
and the view consume it like this:
{{vm.data | json }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With