Is there a way to retrieve the value of bindings in the component controller using Angular 1.5 and Typescript?

In my quest to develop a versatile left-hand menu component that can dynamically display different menu structures based on input strings, I stumbled upon an interesting challenge. By binding a string to the <left-hand-menu-component> element like so:

<left-hand-menu-component module='abc'></left-hand-menu-component>

I aim to have the menu component adjust its structure to reflect the 'abc' module specifically. This requires the controller of the component to efficiently handle the bound data and make relevant service calls.

After extensive research online, I came across helpful resources such as this article, along with this post and discussions on Stackoverflow. The Angular documentation examples, however, felt too simplistic for this specific scenario.

I've attempted to incorporate the provided code samples into my project, but encountered difficulties in getting the controller to successfully interact with the bound value. Is it feasible within a component structure or would it be more suited for a directive implementation?

Has anyone come across a practical demonstration or informative blog post addressing similar components? Any guidance or insights would be greatly appreciated.

Notably, the console logs within the controller constructor currently output 'undefined' as the result.

Component:

module qa.gonogo {
    "use strict";

    export class LeftHandMenuComponent implements ng.IComponentOptions {


        public transclude: boolean = false;
        public controller: Function = LeftHandMenuComponentController;
        public controllerAs: string = "vm";
        public templateUrl: string = "app/content/lefthandmenu/leftHandMenuComponentTemplate.html";
        public bindings: any;

        constructor() {
            this.bindings = {
                module: '<'
            }
        }
    }

    angular
        .module("goNoGo")
        .component("gonogoLefthandmenuComponent", new LeftHandMenuComponent());

}

Controller:

export class LeftHandMenuComponentController implements ILeftHandMenuComponentController {

        menuStructure: IMenuStructure[];
        closeOthers: boolean = true;

        static $inject = [];

        constructor(public module: string) {
            console.log('binding', module);
            console.log('binding2', this.module);
        }

        public $onInit = (): void => {
            this.populateMenuStructure();
        }

Route.

$stateProvider
            .state("bfts",
                <ng.ui.IState>{
                    url: "/bfts",
                    views: <any>{
                        "leftHandMenu": <ng.ui.IState>{
                            template: "<gonogo-lefthandmenu-component module='bfts'></gonogo-lefthandmenu-component>"
                        },
                        "content": <ng.ui.IState>{
                            template: "bfts content"
                        }
                    }
                });

Answer №1

The controller scope has access to the bindings, making this.module function as expected.

I have replicated your code in a plnkr and identified the following issues.

  1. The primary issue is using a "<" binding, which is a one-way binding. This results in an attempt to access the "btfs" variable, which is not defined in your scope, leading to an undefined output. To use a string, utilize "@" as described in https://docs.angularjs.org/guide/component

    constructor() { this.bindings = { module: '@' } }

  2. Avoid injecting the module variable. Instead, define it in your controller to satisfy the typescript compiler.

    public module: string;

  3. Removing the need for controllerAs. The templates automatically receive the scope injected via $ctrl, refer to my example at medium. However, its necessity may vary.

  4. As mentioned in my post, it's beneficial to place angular.module calls at the end of the source file.

Revised code:

angular.module('goNoGo', []);


class LeftHandMenuComponent implements ng.IComponentOptions {


    public transclude: boolean = false;
    public controller: Function = LeftHandMenuComponentController;
    //public controllerAs: string = "vm";
    public template: string = "<div>module :{{$ctrl.module}}</div>";
    public bindings: any;

    constructor() {
        this.bindings = {
            module: '@'
        }
}
}



class LeftHandMenuComponentController {

  menuStructure: IMenuStructure[];
  closeOthers: boolean = true;
  public module: string;

  static $inject = [];

  constructor() {
      console.log('binding2', this.module);
  }

  //public $onInit = (): void => {
    //  this.populateMenuStructure();
}

angular
    .module("goNoGo")
    .component("gonogoLefthandmenuComponent", new LeftHandMenuComponent());

angular.element(document).ready(function () {
  angular.bootstrap(document, ['goNoGo']);
});

You can experiment with the code in plnkr http://plnkr.co/edit/TVI9l8

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

Error class not being applied by Knockout validation

I've implemented knockout validation on a text input and the validation is working correctly. However, the errorMessageClass is not being applied to the error message. I must have made a mistake in my setup, but I can't seem to identify it. My H ...

What is the best way to choose the current Div's ID, as well as its Width and Height properties?

Within this section, there are four div elements with varying widths, heights, and colors that appear and disappear when their respective buttons are clicked. I am adding an "activeDiv" class to the visible div in order to easily select it using that class ...

Angular 2 doesn't reflect changes in component variables in the view until mouseover happens

Since updating from angular2-alpha to the latest version, I've noticed that when a boolean value changes in my *ngIf directive, it doesn't reflect in the view until certain actions are taken. Here is the specific component code: declare var CKE ...

Transform form data from square notation to dot notation using jQuery

During my ajax operations, I noticed that the data being sent is in JSON format. However, when checking Chrome tools -> network XHR, I observed that the form parameters are displayed within square brackets. Example: source[title]:xxxxxxxxxxxx source[th ...

Encountering the issue of receiving "undefined" when utilizing the http .get() method for the first time in Angular 2

When working in Angular, I am attempting to extract data from an endpoint. Below is the service code: export class VideosService { result; constructor(private http: Http, public router: Router) { } getVideos() { this.http.get('http://local ...

What is the best method to eliminate elements from a queue using JavaScript?

I recently attempted to incorporate a queue feature into my JavaScript code. I found some helpful information on this website. While I successfully managed to add items to the queue, I faced difficulties when attempting to remove items from it. var queue ...

Refresh the homepage of a website using React Router by clicking on the site's logo from within the Home component

In most cases, when you click on a website's logo while on the homepage, it typically reloads the page. However, with React, clicking on the logo while already on the Home component does not trigger a reload. Is there a way to work around this issue? ...

Passing all selected items from a list to the controller

I am currently facing an issue with my two multi-select lists. One list contains a full list of names while the second one holds the names that have been selected from the first list. The names are stored in a Vue array which populates the names into the s ...

Accessing a child field from Firebase in a React Native application

My firebase data is structured like this: "Locations" : { "location01" : { "image" : "https://www.senecacollege.ca/content/dam/projects/seneca/homepage-assets/homepage_intl.jpg", "instructorNa ...

I'm looking for the best way to display an error message in HTML using a custom validation directive that I'm creating

<!DOCTYPE html> <html><!--starting of html--> <script src="angular.js"></script> <body ng-app="myApp"> <p>Feel free to type in the input field:</p> <form name="myForm"> <input name="myInput" type=" ...

Oops! The ui-router seems to be having a little hiccup with the animation property not being defined

Upon upgrading my application from angular 1.5.0 to 1.6.5 along with ui-router 1.0.5 (previously using ui-router version 0.2.15), I encountered the error message "Cannot read property '$$animLeave' of undefined". While some routes are functionin ...

Is my implementation of this [^{}]+(?=}) regex pattern in TypeScript accurate?

Hey there! I'm currently working on extracting values that are inside curly braces "{value}". Do you think the regular expression [^{}]+(?=}) I am using is correct? let url = "/{id}/{name}/{age}"; let params = url.match('[^{\}]+(? ...

The Angular router is causing an issue where when navigating back, my component does not reset to 0 as expected, resulting in

I'm currently working on an ionic-angular app and implementing a Register feature where users input their information step by step. The issue I'm facing is with the backward navigation functionality - when users go back using the arrow button, th ...

What is preventing me from using Selenium/Javascript to control Firefox on Ubuntu 22.04, when I am able to do so with Python?

My python script effectively controls Firefox using Selenium: from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Firefox() driver.get("https://dev.to") driver.find_element(By.CLASS_NAME, "crayons ...

Struggling with incorporating a lightbox within an accordion feature in an .html file

I'm currently attempting to integrate this lightbox into this accordion feature. Individually, I've managed to get both elements up and running smoothly. However, when trying to combine them on the same page (regardless of nesting one inside the ...

The variable 'minSum' is being referenced before having a value set to it

const arrSort: number[] = arr.sort(); let minSum: number = 0; arrSort.forEach((a, b) => { if(b > 0){ minSum += minSum + a; console.log(b) } }) console.log(minSum); Even though 'minSum' is defined at the top, TypeScript still throws ...

Learn how to trigger a re-render in React to update a value stored in local storage

I need assistance in displaying a spinner with a percentage value during file uploads within my React application. To achieve this, I am utilizing Material UI's circular progress. My approach involves making a REST call using Axios to obtain the perce ...

When pasting Arabic text into an input box, the words in HTML appear to be jumbled and shuffled around

When I replicate this text يف عام and input it into a box, the output is shown as follows عام يف ...

Type in "Date" and select a date using your mobile device

Hey, does anyone know a good solution for adding placeholder text to an input with type="date"? I'm looking for a way to utilize the phone's built-in date selection feature on a website, rather than having users manually enter dates using the ke ...

The length property cannot be retrieved from an undefined or null reference while executing ctrl.getplaceholder in the ui-select.js file

https://i.stack.imgur.com/lUPm1.png Hey there! I'm currently working on implementing the ui-select angular directive for multiple auto complete. Everything was running smoothly with Angular version 1.2.18, but as soon as I upgraded to Angular 1.5.5, ...