Using the bind method to update "this" within Angular controller's context

Currently, I am utilizing Angular's new router components alongside JavaScript. Within my codebase, there are multiple controllers similar to the example below.

My goal is to implement a single function to all controllers so that I do not have to repeat it in each one individually.


        function HomeController(authService, factoryClient) {
            console.log('this is home controller');
            this = doCommonController.bind(this); // encountering an error here
            // The 'this' object should comprise currentUser, authService, logout, and testVar properties
            console.log(this);
        }
    

The function in question is:


        var doCommonController = function (authService, currentUser) {
            this.testVar = 'value';
            this.authService = authService;
            this.currentUser = currentUser;
            this.logout = this.authService.logout;
        }
    

Additionally, how can I transmit the authService and factoryClient from the controller to be accessible within doCommonController?

Answer №1

Make sure to utilize .call() instead of .bind(). Additionally, avoid assigning any invalid values to this.

function HomePageController(authService, factoryClient) {
    console.log('this is the home page controller');
    var currentUser;
    executeCommonController.call(this, authService, currentUser); // results in an error
    // at this point, 'this' should contain currentUser, authService, logout, and testVariable
    console.log(this);
}

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

Arranging sequence of jQuery functions

I have implemented a loop using jQuery that iterates through specific elements on an HTML page. During each iteration, I switch over a variable and add HTML code to particular locations. The issue arises when one of the appends requires importing another ...

Executing a JavaScript function within the HTML body and passing a variable as an argument to the function

I recently created the following HTML code: <html> <title> Upload Infected File </title> <body> <header id = "header"> <h1 align="center">Upload Malware File</h1> <p align="center"> Pleas ...

Creating a dynamic dropdown in a Rails application using the simple_form gem

In my Rails application, I have a straightforward has_many and belongs_to relationship. Using simple_form, I am looking to dynamically adjust the dropdown options based on the selection made by the user. Models class Processor < ApplicationRecord ...

Locate a group of DOM selectors that correspond to the highlighted text

Imagine you're at a certain location and you highlight some text: https://i.sstatic.net/8PGvD.png When you inspect the DOM, you see it's represented like this: https://i.sstatic.net/rL0Og.png The actual text is: "Local embassy – For Wikiped ...

Having trouble logging in with the script, even though I have already set up the correct username and password in my

After purchasing the "Jqcm - Premium Responsive Quiz Engine" script, the author has disappeared and has not been responding to any questions for months. When attempting to log in to the backend with the provided username and password, a circling bar appea ...

Error with Expression Engine: PHP function cannot be executed

I have been attempting to execute a PHP Script with ExpressionEngine tags using Ajax on my webpage. I followed the documentation and set up the PHP script accordingly, but it appears that I am unable to call the function in the PHP script. There must be so ...

Alternative method to jQuery's "find" selector

$('.wrapper a').filter('a'); //returns all anchors I am trying to find a way to select all anchor elements using a specific selector. The issue is that the find method only looks at descendants, so I need an alternative solution. Any s ...

Rotating a non-centered triangle geometry in ThreeJS

I've been struggling to understand why my triangle isn't rotating around the center as I expected. My goal is to have two triangles side by side, with one rotated 60 degrees. However, when I rotate them, all corners should remain the same size. ...

Synchronizing subscriptions

Currently, I am engaged in a project for my organization and am strictly upholding the Non-Disclosure Agreement (NDA) that I have signed. In adherence to this confidentiality agreement, I present the following code snippet devoid of any sensitive details: ...

Comparing strings in arrays using JavaScript

Currently, I am engrossed in a firebase project involving vuejs. My goal is to create a chart that visually represents the number of subscribers per month. The tricky part lies in accurately calculating the number of user profiles created each month. As fo ...

Learn the process of adjusting opacity for a specific color in CSS

At the moment, this is the code I'm using to apply a color to an element using jss. const styleSheet = theme => ({ root: { backgroundColor: theme.colors.red, }, }) I am interested in finding out if there is a way to add opacity based o ...

Develop and arrange badge components using Material UI

I'm new to material ui and I want to design colored rounded squares with a letter inside placed on a card component, similar to the image below. https://i.stack.imgur.com/fmdi4.png As shown in the example, the colored square with "A" acts as a badge ...

Implementing authentication with JSONP requests in Angular

When using JSONP on a request with basic auth, it is necessary to include the Authorization header in the request to retrieve the token. Upon testing this: $scope.doRequest = function() { $http({method: 'JSONP', url: 'http://apilder-ap ...

Exploring the Basics of MVC Routing in Express/Node.js

I am encountering an issue with routing in my application. I have set up a main index.js router, a secondary router file, and a controller, but for some reason, it is not routing correctly and results in a 404 error. Here is the content of routers/index.j ...

Error message from Google Adsense: The registration landing URL modifier is null

For the past few days, I've been encountering a persistent error message on all web pages where I have Adsense banners: "Uncaught TypeError: Cannot call method 'registerLandingUrlModifier' of null" I have been using the asynchronous script ...

Retrieve specific attributes in a nested eager loading sequelize query

I have a query to fetch information about shows from a database, along with details about the venue and bands involved. However, I am only interested in retrieving the names of the bands and the venue. The current code is pulling the entire record instea ...

A guide on transferring information to a database through a WYSIWYG HTML JavaScript editor in conjunction with Django

This morning, I dedicated my time to going through numerous tutorials on YouTube that explain how to build your own WYSIWYG editor. After testing the code in a controlled environment, it seems to function correctly and delivers the customization promised. ...

Having trouble copying an iframe from one div to another div?

I'm having trouble transferring an iframe to another div. Here is the code I am using: <script type="text/javascript"> $(document).ready(function () { setInterval(function () { if ($('#d1').html() != $('#d ...

Utilizing Angular's $resource method for creating HTTP POST

I've managed to make the GET example work, however, I'm having issues with 'doSave' for POST. Am I missing something here? $scope.obj1 = $resource('http://localhost:port/srv/:id', {port: '\:8080&ap ...

Separate a JSON string into smaller parts and showcase each part using ng-repeat

<div ng-controller="countryCtrl"> <div class="m-b-20" ng-repeat="val in records"> {{val.Country}} <br> </div> </div> var app = angular.module('app', []) .controller('countryCtrl', ['$scope&a ...