Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying content in Angular without $scope

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);
  }

]);
like image 923
anon Avatar asked Apr 18 '26 18:04

anon


2 Answers

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.

like image 137
Pankaj Parkar Avatar answered Apr 20 '26 07:04

Pankaj Parkar


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 }}
like image 43
Radim Köhler Avatar answered Apr 20 '26 07:04

Radim Köhler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!