Using the AngularJS component, one can easily implement the $translate feature

I am currently working on integrating the $translate.proposedLanguage() function into an AngularJS component to set up and configure the intl-tel-input plugin:

function customTel() {
return {
    restrict: 'A', // restriction as Attr
    require: 'ngModel', // requirement of ngModel from html
    scope: {},
    link: function($scope, $elem, $attrs, $ctrl) {

        var ngModelCtrl = $ctrl; // access ngModel using $ctrl

        var language = $translate.proposedLanguage() || $translate.use();

        if (language === "es") {
            language = "ES";
        } else if (language === "en") {
            language = "GB";
        } else if (language === "pt-pt") {
            language = "PT"
        }

        $elem.intlTelInput({
            initialCountry: language,
            preferredCountries: ["ES", "GB", "PT", "US"],
            nationalMode: true,

            utilsScript: "../../webclientes/bower_components/intl-tel-input/build/js/utils.js"
        });

    }
}
}

    angular
        .module('webclientesApp')
        .directive('customTel', customTel);

The issue I am facing is that $language appears to be undefined, despite being injected in the controller:

(function() {
    'use strict';

    angular
        .module('webclientesApp')
        .controller('ContactaController', ContactaController);

    ContactaController.$inject = ['$scope', 'Principal', 'ContactaServiceRest', '$state', '$translate'];

    function ContactaController ($scope, Principal, ContactaServiceRest, $state, $translate) {

...

I have attempted injecting it into the link parameter or within the .directive section below, but so far, nothing seems to work.

Is there a way to access $translate through the component? Appreciate any insights!

Answer №1

By making this simple adjustment to your code, it should function properly:

angular
.module('webclientesApp')
.directive('customTel', customTel);

customTel.$inject = ['$translate'];

function customTel($translate) {
    return {
        restrict: 'A', 
        require: 'ngModel', 
        scope: {},
        link: function ($scope, $elem, $attrs, $ctrl) {

            var ngModelCtrl = $ctrl; 

            var language = $translate.proposedLanguage() || $translate.use();

            if (language === "es") {
                language = "ES";
            } else if (language === "en") {
                language = "GB";
            } else if (language === "pt-pt") {
                language = "PT"
            }

            $elem.intlTelInput({
                initialCountry: language,
                preferredCountries: ["ES", "GB", "PT", "US"],
                nationalMode: true,

                utilsScript: "../../webclientes/bower_components/intl-tel-input/build/js/utils.js"
            });

        }
    }
}

It's important to remember to inject dependencies in the directive function rather than the link function. If you are encountering injection errors, consider enabling a setting in Angular, which you can learn more about in the documentation. This method not only resolves any issues but also allows for easier minification of files.

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

Unable to find JSON data using the Javascript Kafka Magic Tool, as no results are being

In JSON format, I have a message that contains various details. My goal is to utilize Javascript search functionality to identify if the EmailAddress matches the specific value I am looking for within hundreds of similar messages: "Message": { ...

Displaying an 'undefined' message in a JavaScript alert box

Hello! Just made the switch from C#/C++ to JavaScript recently and I'm really enjoying it. I've encountered a behavior that has me scratching my head, can anyone help explain? So here's what's happening: when I run this script, I see ...

What is the best way to bring in an external webpage using Jquery and Custom variables into an Iframe?

Is it possible to use JQuery to load a page into an iframe? I have a specific page that generates a custom printable PDF and I want it to be loaded into an iframe for user convenience. Since I utilize jQuery to fetch all the necessary variables, I cannot ...

Issue occurred while trying to set the value from an API call response in the componentDidMount lifecycle method

There is a boolean variable disableButton: boolean; that needs to be set based on the response received from this API call: async getDocStatus(policy: string): Promise<boolean> { return await ApiService.getData(this.apiUrl + policy + this.myEndpo ...

Upon installation of Next.js, an error in the globals.css file quickly emerged, yet remarkably, it did not disrupt the code in

Here is the link to the repository: here. Once I created the next.js environment using the command "npx create-next-app@latest ./" and ran "npm run dev", I encountered the following error message:- ../../../#React Projects/My projects/causs/styles/global. ...

Utilizing d3.js to filter a dataset based on dropdown selection

I am working with a data set that contains country names as key attributes. When I select a country from a dropdown menu, I want to subset the dataset to display only values related to the selected country. However, my current code is only outputting [obje ...

How can I display milliseconds from a date in Angular2+?

I recently encountered an issue while working with a custom pipe that was used to display time. I attempted to modify it so that it could also show milliseconds: {{log.LogDate|jsonDate|date:'dd.MM.yyyy &nbsp; HH:mm:ss.sss'}} Here is the cod ...

Using the 'client-side rendering' and runtime environment variables in Next.js with the App Router

In the documentation for next.js, it's mentioned that runtime environment variables can be utilized on dynamically rendered pages. The test scenario being discussed involves a Next.js 14 project with an app router. On the page below, the environment ...

Updating data in React Native fails to activate useEffect, leading to the screen not being refreshed

I'm facing a challenge while working on a recipes app using Firebase Realtime database. I have a functional prototype, but I am encountering an issue where the useEffect hook does not trigger a reload after editing the array [presentIngredients]. Her ...

Conceal content upon initial page load, then unveil after a set period of time

Is there a way to hide a paragraph on page load and reveal it after a certain amount of time has passed? I assume JavaScript will be needed, but I'm not sure where to begin. Any suggestions? ...

Guide on transferring files between Node.js/Express servers from receiving files at Server A to sending files to Server B

Currently, I'm tackling node.js express servers and I've hit a roadblock! Despite my efforts to scour the documentation and other resources, I can't seem to find the right solution. Here's what I need to accomplish: Receive 2-3 PDF ...

Modify the initial letter of the user input as it is entered using JQuery

I've been experimenting with auto-capitalizing the first character that a user inputs in a textarea or input field. My initial approach was as follows: $(document).ready(function() { $('input').on('keydown', function() { if ( ...

Is there a way to retrieve the size of a three.js group element?

Obtaining the dimensions of a mesh (Three.Mesh) can be done using the following code: mymesh.geometry.computeBoundingBox() var bbox = mymesh.geometry.boundingBox; var bboxWidth = bbox.max.x - bbox.min.x; var bboxHeight = bbox.max.y - bbox.min.y; var bbo ...

Retrieve a document utilizing XHR on iOS Safari platform

I'm currently working on adding the capability to download a file stored on a server. To access the file, I need to include the Authorization header, requiring me to send an XHR request to retrieve the file from the server. Since the file content is s ...

Ensuring the website retains the user's chosen theme upon reloading

I have been developing a ToDo App using MongoDB, EJS, and Node JS. My current challenge involves implementing a theme changer button that successfully changes colors when clicked. However, whenever a new item is added to the database, the page reloads caus ...

Utilizing jQuery AJAX to Send an HTML Array to PHP

In my current HTML forms and jQuery AJAX workflow within the Codeigniter Framework, I've encountered a common issue that has yet to be resolved to suit my specific requirements. Here's the situation: HTML - The form includes an array named addre ...

Vue Testing Utilities - issue with data not updating upon click event activation

I recently created a basic test using Vue Test Utils: import { mount } from '@vue/test-utils' const App = { template: ` <p>Count: {{ count }}</p> <button @click="handleClick">Increment</button> `, ...

Using MongoDB to group by the difference in dates and retrieve the hour value

Currently, I am working on an application and I require some information from my database: I have a model called "traitement" which includes a user, The "traitement" model has a start date and an end date, both in Date format, allowing MongoDB to use ISO ...

Exploring the process of implementing smooth transitions when toggling between light and dark modes using JavaScript

var container = document.querySelector(".container") var light2 = document.getElementById("light"); var dark2 = document.getElementById("dark"); light2.addEventListener('click', lightMode); function lightMode(){ contai ...

When working with Vue in Laravel, the console may show that app.message is returning undefined

Recently, I embarked on my journey to learn Vue and have been closely following their introductory guide. However, I seem to be facing a hurdle at this point: Simply open your browser’s JavaScript console and adjust app.message to a different value. I ...