When working with Angular1+ ES6 and using controller as a class, the utilization of Dependency Injections may be ambiguous within controller functions

I recently started using ES6 class for defining my controller, and here is the syntax I am using:

export class SearchBarController {
    constructor($log) {
        'ngInject';

        $log.debug("Hello");
    }

    textTyped($log){

        $log.debug("change fired.");
    }
} 

In the view :

<input type="text" data-ng-model="vm.txt" data-ng-change="vm.textTyped()"/>

The issue I am facing is that although "Hello" from within the constructor gets logged successfully, "change fired" within the typedText() function does not fire because it is apparently undefined. How can I ensure that my class function textTyped() has access to the $log service?

Please Note: If I assign $log to a class property in the constructor like this,

this.logger = $log;

And then use it like this,

this.logger.debug("Change fired.");

it works. However, I am unsure if this is the correct approach.

Update: Additionally, this approach exposes the this reference to the $log service in the view associated with this controller. Is this potentially harmful?

Is there a more optimal solution?

Answer №1

this.logger = $log;

As you correctly noted, this is the correct approach. Due to its nature as an object, there is no reliance on a global scope.

Answer №2

class NavigationController {
    constructor($scope, $log) {
        this.logger = $log;

        // Assigning to scope
        $scope.vm = this;
    }

    textTyped(){
        this.logger.debug("Text change detected.");
    }
}

SearchBarController.$inject = ['$scope', '$log'];

Give it a shot with this approach

Answer №3

If you're curious, I've come across a more elegant solution to the issue by utilizing ES6 Object Destructuring :

class ABCController {
    constructor($log, $http){
        let vm = this;
        vm.DI = () => ({$log, $http});
    }

    classFn(){
        let vm = this;
        let {$log, $http} = vm.DI();
        //Now utilize $log and $http directly

        $log.debug("Testing");
        $http({...}).then();
    }

    classFn2(){
        let vm = this;
        //You can also destructure only the necessary dependencies in this manner
        let {$http} = vm.DI();
    }
}
ABCController.$inject = ['$log', '$http'];

This approach eliminates the need for writing messy/confusing code like vm.DI.log, etc. Moreover, it ensures that the DIs are less exposed in the view.

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

What method does AngularJS use to distinguish between these two properties?

I grasp the concept that ng-model generates a property that corresponds to the {{name}}. How does AngularJS distinguish between the {{name}} derived from the ng-model and the {{name}} originating from the ng-repeat/ng-init? <section class="section"> ...

How can I retrieve values from JSP style tags in an AngularJS HTML view?

How can I retrieve JSP style tag values in an angularjs html view? Specifically, is it possible to extract the ‘principal.firstName’ value from the following tag in the browser and is there an Angularjs approach to achieve this? <sec:authentication ...

A guide to injecting HTML banner code with pure Vanilla Javascript

Looking for a solution to incorporate banner code dynamically into an existing block of HTML on a static page without altering the original code? <div class="wrapper"><img class="lazyload" src="/img/foo01.jpg"></div> <div class="wrapp ...

Passing state updates between child components by utilizing the useReducer hook and dispatching actions

Check out this interactive example on CodeSandbox with the code provided and highlighted linting issues: https://codesandbox.io/s/react-repl-bw2h1 Here is a simple demonstration of my current project setup. In a container component, there is an important ...

Managing simultaneous access to a variable in NodeJS: Best practices

For instance: var i = 0; while(true) http.request('a url', callback_f); function **callback_f**(){ **i++**; } In this straightforward scenario, multiple requests could unintentionally increase the value of i simultaneously. How can I creat ...

Modifying Arrays with Different Data Structures in JavaScript

I am interested in implementing the following scenario: var A = ["Jon","Brad","Rachel"]; var B = ["Male","Male","Female"]; var C = [ {"Jon","Male"}, {"Brad","Male"}, {"Rachel","Female"} ] Can you guide me on how to retrieve var C using javascrip ...

How can you retrieve the X.509 Certificate from a P12 file using Node JS?

I obtained a p12 file that contains an X.509 Certificate. To handle this file, I am utilizing the forge library: var forge = require('node-forge'); var fs = require('fs'); var keyFile = fs.readFileSync("/path/to/p12/file.p12", 'b ...

Error: Running the command 'yarn eg:'live-server'' is not a valid internal or external command

Currently, I am utilizing yarn v1.6.0 to manage dependencies. I have globally installed live-server by running the following command: yarn global-add live-server However, upon executing it as live server, I encounter the following error: 'live-ser ...

Tips on converting comma-separated values into HTML table rows using <tr> tags

JSON Data { "catalog_name": ["Sistem Autodownline ", "Karipap Pusing Ayu"], "price": ["100", "8"], "qty": "", "qty2": ["", ""], "total_qty": "", "total": "", "mem": "10", "email_2": "", "ic_add": "890527-08-6136", "c ...

What is the best way to eliminate the first even number from a string?

My task involves working with a string containing only numbers. For example: let inputString = "1234"; The Challenge I need to create a function that will return the string excluding the first even number, if one exists. Example Output: " ...

I encountered a parsing issue while trying to compile my Vue project

Issue: The component name "Header" should always consist of multiple words. Fix: Change the component name to a multi-word format according to Vue standards (vue/multi-word-component-names). ...

Is it possible to use Ajax to prompt a pop-up window for basic authentication when logging in?

While attempting to access the reed.co.uk REST web API in order to retrieve all related jobs, I am encountering an issue. Despite passing my username and password, a popup window keeps appearing when I call the URL. The alert message displayed reads: i ...

Creating crawlable AMP versions of Angular websites

Having an Angular website where I dynamically load object properties, I am creating separate AMP sites for each of these objects. Typically, I would link to the AMP site from the canonical site. However, the issue arises because the crawler cannot find the ...

How can I transmit a pong frame using WebSocket in javascript/NodeJS?

I am struggling to locate a proper example demonstrating how to send a PONG response using javascript/NodeJS within the context of a WebSocket connection (back to a server that requests it after sending a PING request). Can anyone provide guidance on thi ...

Encountering issues with resolving controller parameters in AngularJS

I am currently facing an issue with my angular application. It works perfectly fine on my local machine, but when I try to move it to the Test Server, it doesn't work as expected. My current file structure looks like this: -- Controller -- -- AContr ...

Adding router to controller method within Laravel 5

I'm curious as to why controller method injection in Laravel 5 cannot be used to make the $router singleton available inside a controllers method. Here's an example of what I mean: use Illuminate\Routing\Router; class WelcomeControlle ...

JQuery Slider's Hidden Feature: Functioning Perfectly Despite Being Invisible

Having an issue with a jQuery slider on my local HTML page. The sliders are not showing up as intended. I want it to display like this example: http://jsfiddle.net/RwfFH/143/ HTML <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery ...

Various colored backgrounds in a random arrangement on a grid post layout

I'm looking to implement this plugin for displaying blog posts, but instead of using an image as the background, my client wants different colored images. I have managed to figure out the code to achieve this based on a post I found here, but unfortun ...

Method not found in Angular

I am currently working on an Angular application with a C# backend that exposes services. I am trying to use AngularJS resources to access these services. However, when I call the resource in the controller, I am encountering the following error: TypeErro ...

Retrieve Cookie from a designated domain using Express

I am currently working on a React application that communicates with a Node/Express backend. To ensure the validity of requests, I am sending a cookie created by react-cookie from the React app to the Express app. To avoid issues related to naming conflict ...