Finding solutions using a controller class

I have a component that uses a controller class and accepts an input parameter through the use of a bindings object. In the controller, I am able to access the parameter after the constructor runs, but I cannot pass it as a constructor parameter.

While working on a plunker (a coding playground), I discovered a potential solution using the $onInit method (as stated in the ui-router documentation).

Is this the correct approach? I hope this information is helpful to someone, and please let me know if there are any ways to improve it.

Here is an example of the controller:

class Controller {
  constructor(){
    'ngInject';
    this.$onInit = function(){      // Comment this
       this.problemScopeHere = angular.copy(this.param);  
    }                               // Comment this
    console.log(this.param);            
  }
  get(){
    this.problemScopeHere = this.param;
  }
}

And here is an example of the component:

 let Component = {
   bindings : {
      param : "="
   },
   controller : Controller,
   controllerAs: '$ctrl',
   templateUrl: 'component.html'
};

let app = angular.module('app', ['ui.router']);
app.component('comp', Component);

Answer №1

I suggest utilizing the resolve method in your case, as it allows for routing to components with the current version of UI Router. You can refer to the documentation on routing to component:

.state('app.home' ,{
      url: '/home',
      component: 'comp',
      bindings: {
        param: 'param',
      },
      resolve: {
        paramData: function () {
          return {
            string: 'I am the object param'
          }
        }
      }
    });

Here's a working example (slightly different from yours since I'm not sure if home.html is necessary – it might just be for demonstration purposes): https://plnkr.co/edit/jaXQN7YmmkI8AC1DxohI?p=preview. Additionally, note that you cannot use bindings before the first $onChanges event (the first run occurs right before $onInit) or until $onInit itself runs. In Angular 1.6 and above, it is recommended not to rely on them in the constructor. Instead, you can trust them in $onInit, which is considered the most modern approach. Previously, I used to pass parameters within the template. However, with UI Router 1.x, it has become easier. You can declare $onInit as a regular class method. Moreover, there's no need to use controllerAs: $ctrl. The default value is set to $ctrl if you don't provide one, but for consistency across all your components, I strongly encourage you to always specify a default value.

Answer №2

Simply include the parameter as an attribute within your controller class.

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

AngularJS application failing to initialize without a module being included

I'm feeling a bit lost when it comes to angularjs and I have a question about why my angularjs app is refusing to bootstrap without creating a module, even though egghead.io and other tutorials seem to suggest otherwise. Here's a snippet of my HT ...

Issues with AngularJS UI Router functionality are being experienced specifically on localhost

What is causing the discrepancy in UI-Router functionality between JSFiddle and localhost? The localhost link is http://127.0.0.1:54046/preview/app/index.html. Have I overlooked something crucial here? There are no visible JS errors present in the console. ...

How to fetch data from DynamoDB using AngularJS

I've been working on retrieving a value from DynamoDB and then assigning that value to ng-model in order to display it. However, I keep running into the issue of the data always being null. DynamoDB table "meta_value": { "clause_note": "Note: go ...

Struggling to run this unit test (for a helper) smoothly - AngularJS, Karma, Jasmine - Any tips?

As a newcomer to Angular and Karma, the abundance of conflicting advice on how to write unit tests is making things incredibly confusing for me. Any help you can offer would be greatly appreciated! I am currently working on a helper class that relies on a ...

What is the best way to retrieve all designs from CouchDB?

I have been working on my application using a combination of CouchDB and Angular technologies. To retrieve all documents, I have implemented the following function: getCommsHistory() { let defer = this.$q.defer(); this.localCommsHistoryDB ...

My UI-view is not receiving the injected components

Currently, I am in the process of setting up a boilerplate for angular 1.5.9 utilizing UI Router 1.0.0. While I have successfully displayed my parent state component within the ui-view, I am facing an issue when trying to nest states within the parent - th ...

Icons from Material Design Lite are not appearing as expected when integrated into an Angular project

Recently, I integrated MDL into my Angular project. While most of it is functioning properly, the MDL icons seem to be giving me trouble... I've implemented them using <i class="material-icons">share</i>, but instead of displaying as an i ...

Exploring the capabilities of nested forEach loops in Angular

Consider the following two arrays: var array1 = [{'target_object_id': 1, 'extra': 'ok'}, {'target_object_id': 2, 'extra': 'ok'}] var array2 = [{'id': 4}, {'id': 2}] The obje ...

Execute the function when the control becomes visible

Currently, I possess an input control: <input id="someID" class="form-control" type="text" name="SomeData" data-ng-model="vm.SomeData"> I have a requirement to set the initial value of vm.SomeData upon user scrolling down to this control. As a begi ...

AngularJS: The $http.get request for JSON data from eBay is malfunctioning

I'm feeling lost and needing some guidance. When I make an ebay search request, the browser displays a JSON response. I saved this JSON in a file named v1 on my website. However, when I tried to access it through a $http.get request, it returned null. ...

Limiting the results of an Angular ng-repeat to a specific timeframe

Looking to showcase the most popular items from the last 24 hours based on this Model. { "_id": { "$oid": "56abe20fabd3fa64187b5d21" }, "user": { "$oid": "56a1832a36dc3d0e00c7aa3f" }, "title": "Intel Pentium i5 Quad ...

Issue with updating state in Python Flask Angular application

I'm currently developing an application using Flask, Angular, and MongoDB. I've implemented state provider in Angular, and everything is loading correctly within the application. However, upon refreshing the page, a 404 error is being thrown. A ...

Encountering an unexpected token error while using JSON.parse()

When attempting to parse this JSON string, I encounter an error indicating an unexpected token $scope.feeds = JSON.parse('[{"id":"212216417436_10152811286407437","from":{ "category":"Movie","name":"The Lord of the Rings Trilogy","id":"212216417436"}, ...

Instructions for modifying the color of the close button in the angularjs ui-select module

I am currently using ui-select for multiple selection in a dropdown. When an item is selected, it displays a cross button on the upper right corner of the selected item. Is there a way to change the color of the cross button to red? <ui-select multip ...

Utilizing the indexOf Method in AngularJS

Here is my array: emp=["111","56"]. This is the code I have: <input type="text" placeholder="Enter" class="form-control" name="Emp" ng-model="myModel.Emp" ng-required="currentStep ==2"/> <input type="text" placeholder="Enter" class="form-contro ...

How can I connect ng-options to retrieve data from a remote JSON source?

Is it possible to use AngularJS to bind select options to a remote data source without needing an intermediate field? I'm not completely sure about this. For instance, the desired HTML would look like: <select ng-model="city" ng-options="obj for ...

Limit Use of Special Characters in HTML and AngularJS

` ~ ! @ # $ % ^ & * ( ) _ + = { } | [ ] \ : ' ; " < > ? , . / I need to limit the use of special characters and numbers in the input field. To achieve this, I have employed the following pattern: ng-pattern="/^[a-zA-Z ]*$/" This patt ...

Issues arise when socket events fail to trigger in a web browser when utilizing docker containers and docker-compose

Before dockerizing the application, all functions as expected. However, after migrating the application to Docker, I am experiencing issues with receiving socket events in the browser. The server can still receive socket events from the browser and conso ...

Basic application - angular has not been declared

I'm currently diving into the realm of javascript and angularjs, following along with the tutorials on . After setting up a basic IntelliJ javascript project, I created two essential files: index.html <!DOCTYPE html> <html lang="en"> ...

Using ng-repeat in Angular JS to generate forms

Having just recently delved into angular JS, I began working on it a mere week ago. Utilizing the Angular-UI Bootstrap Tabs directive in my application, upon load, a grid displaying a list of records is presented within a static tab. Once a user selects a ...