Showing information in Angular without using $scope

When working with Angular and angular UI-Router, my goal is to display content without relying on $scope.

In my mainController, using directives like ng-repeat is no problem. However, I am struggling to access information from my postsController.

Despite successfully retrieving the correct data in my controller (as shown by console.log), I am unsure of how to access it further.

index.html

<script type="text/ng-template" id="/posts.html" >

    {{ }} // What should be inserted 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);
  }

]);

Answer №1

To implement controllerAs, you need to define your controller as shown below. By providing an alias for your controller, you can easily display data on the view.

.state('items', {
    url: '/items/{id}',
    templateUrl: '/items.html',
    controller: 'itemsController as itemCtrl'
});

View

<script type="text/ng-template" id="/items.html" >
    <ul>
      <li ng-repeat="i in itemCtrl.items">{{i}}</li>
    </ul>
</script>

Make sure you are using the latest version, ideally above 0.2.0+, of ui-router to utilize controllerAs. If you are on an older version, you can follow @RadimKöhler's suggestion instead.

Answer №2

It is recommended to utilize the controllerAs declaration:

.state('posts', {
    url: '/posts/{id}',
    templateUrl: '/posts.html',
    controller: 'postsController',
    controllerAs: 'vm' // this alias will be injected into $scope
  });

Then, the view can access it in this manner:

{{vm.data | json }}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on displaying a grid in the center of the screen with a vertical sliding feature

I've noticed certain apps displaying a grid view or form on an alert box with vertical sliding, but I'm clueless about how to make it happen. As far as I know, this can be achieved using jQuery.. Any assistance would be greatly appreciated. Th ...

Update the designated dropdown menu using its identification number

I have discovered a way to change the selected dropdown item by value, but I am interested in doing it by the option ID instead. The reason for this is that the values are dynamically generated. Currently, I am working on creating a questionnaire that incl ...

Having difficulties with AngularJS routing

This has got to be the most novice question I've ever asked. Check out my code snippet below: App.js: window.app = angular.module("my_super_app", [ 'router', 'ng-rails-csrf' ]); router.js: angular.module("router", ['n ...

Dealing with reactive form controls using HTML select elements

I am working with a template that looks like this: <form [formGroup]="form"> <mdl-textfield type="text" #userFirstName name="lastName" label="{{'FIRSTNAME' | translate}}" pattern="[A-Z,a-zéè]*" error-msg ...

Does ng-bind have the ability to function with input elements too?

My mind was spinning as I tried to figure out why my <input ng-bind="x.a * x.b" tabindex="-1" readonly/> expression wasn't functioning. The use of ng-model was not an option due to the fact that the product is not an L-value, so I made the swi ...

GraphQL/Relay Schema "Field cannot be queried..."

I'm encountering an issue when trying to query specific fields in graphql/relay. My goal is to retrieve the "courseName" field for Courses from the schema provided below. For instance, if I query the User with: { user(id:1){firstname,lastname}} T ...

Encasing shaka-player within an AngularJS directive is causing an issue (specifically, the error "this.target.addEventListener is not

I am looking to implement the shaka-player example into an AngularJS directive. The stand-alone example player functions properly and can successfully play the MPEG-DASH version of Big Buck Bunny hosted on Akamai's CDN. However, upon attempting to u ...

Issues with Angular's http get functionality not functioning as expected

I'm experimenting with an API on apiary.io and attempting to retrieve data from it using Angular, but I'm encountering issues with the call. The setup seems straightforward, so I'm not quite sure what's causing the problem: HTML: < ...

How to align an image in the center of a circular flex container

I'm facing an issue in my Angular project where I have the following code snippet: onChange(event: any) { var reader = new FileReader(); reader.onload = (event: any) => { this.url = event.target.result; }; reader.readAsData ...

Concealing and Revealing a Div Element in HTML

Every time the page is refreshed, I am encountering a strange issue where I need to double click a button in order to hide a block. Below is the code snippet for reference: <!DOCTYPE html> <html> <head> <meta name="viewport&quo ...

Bootstrap typehead not activating jQuery AJAX request

I am attempting to create a Twitter Bootstrap typehead using Ajax, but nothing seems to be happening. There are no errors and no output being generated. Here is the jQuery Ajax code I have implemented: function CallData() { $('input.typeahea ...

Issue locating the bottom of the scroll bar

My attempt to detect when the scroll reaches the bottom of a div involves using this code: $('.scrollpane').scroll(function(){ if ($(this).scrollTop() + $(this).height() === $("#results").height()) { alert('scroll at bottom&a ...

Prevent mdDialog from automatically resizing to fit content upon opening

I am currently using a material design $mdDialog that includes a search bar. I've noticed that when the search results are shorter (with fewer characters), the dialog automatically shrinks to fit the width. Is there a method to set the initial width o ...

Having difficulty retrieving the JSON response using AngularJS

Looking to retrieve the build values from apache.org using their API link: I attempted to use angularjs $http.jsonp to fetch the data, but encountered difficulties. In the Chrome console, the JSON API loads successfully in the network tab, but the actual ...

What is the process for importing a class (.js file) into a .vue file?

I am facing an issue with my Vue application. I have created a class named `Authenticator` in the file `Authenticator.js`, and now I need to utilize its functions in my `Login.vue` file. Could someone guide me on how to properly export the `Authenticator` ...

Can you explain what findDOMNode is and why it is no longer supported in StrictMode within the console?

I attempted to create a count-up feature using React visibility sensor and React count up, but encountered an error in the console. Is there a correct solution to this issue? Caution: The use of findDOMNode is deprecated in StrictMode. This method was uti ...

Issue with Bootstrap Carousel Interval Setting not Functioning as Expected

I recently added Twitter Bootstrap-Carousel to a website with the intention of using it to navigate through different sections of a module. However, I'm encountering an issue where setting the interval to false does not work as expected. When I set an ...

"Encountering a delay in the passport authentication callback process

After multiple attempts to solve this issue independently, I have turned to the Stack Overflow community in search of guidance. I am implementing user authentication using passport. It has already been initialized in my main express.js file following the ...

The function of cookieParser() is causing confusion

Having an issue that I've been searching for answers to without success. When using app.use(express.cookieParser('Secret'));, how can we ensure that the 'Secret' is truly kept secret? I'm feeling a bit lost on this topic. Is ...

Exploring the nuances of AngularJS testing with Jasmine and Karma: delving into the differences between using beforeEach() with

I am new to Jasmine and Karma testing, specifically when it comes to unit testing AngularJS services. When writing specs, I encountered two different ways of injecting a module into the test. 1st Type beforeEach(angular.mock.module("app")); 2nd Type be ...