Passing Angular properties to an external JavaScript file

How do I Send Parameters from AngularJS To JS File?

I've been attempting to transfer data from Angular to an external JS File for quite some time now. I've tried using ng-model, ng-init, ng-bind and two-way directives without success.

<body lang="en" ng-app="app" ng-model="baseUrl='http://example.com'" >
<body lang="en" ng-app="app" ng-init=="baseUrl='http://example.com'" >

---- javascript

var app = angular.module('app', ['ui.grid','ui.grid.pagination']);
var baseUrl;

etc..etc..

All the information I come across regarding Angular Directives is about retrieving data from a JavaScript variable. However, I need to assign a value from Angular to a JS file instead.

The only solution I found so far is to use:

    <script>
    var global = {
        baseUrl: 'http://example.com'
    };    
    </script>

before declaring

<body lang="en" ng-app="app" ng-model="baseUrl='http://example.com'" >

in the HTML

Unfortunately, this approach doesn't work for me. Is there another workaround available? Any feedback would be greatly appreciated :)

Answer №1

It is not recommended to use directives for modifying global data as that task should be handled by a service or controller. However, if you choose to disregard this advice, you can place your logic in a lifecycle method of the directive. One way to do this is by adding it to the link function. This approach may be considered a workaround, but I have already mentioned that.

var myModule = angular.module(...);

myModule.directive('directiveName', function factory(injectables) {
  var directiveDefinitionObject = {
    link: function postLink(scope, iElement, iAttrs) { 
       window.myGlobalVariable = 'Living dangerously';
    }
  };
  return directiveDefinitionObject;
});

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

Tips for updating values in an Angular model and pushing it to an array with the specified index

I am currently facing an issue with my Angular Model as I attempt to add it to an array in order to generate repeated fields. The purpose of this array is to then be looped through in order to create HTML fields within a component. However, during the proc ...

Is the order of execution alternating when resolving a promise from an external one?

As I was exploring the resolution of promises within one another, I came across some intriguing behavior: const someTask = callback => { new Promise(res => res()) .then(() => callback()) .then(() => console.log("A 1!")) .then(( ...

The Material-ui paper component fails to display on the screen

The material-ui paper component is implemented on my homepage and functioning correctly. However, when navigating to another page and returning to the homepage, the paper component disappears, leaving only text rendered. Can you help me identify the issue? ...

The resize function triggers twice as many events with each window resize

While working on my website, I encountered a navigation issue when resizing the browser from desktop to mobile size. Initially, the mobile menu worked on load, as did the desktop navigation. However, after running a script with $(window).on('resize&ap ...

Utilizing ReactJS alongside either jQuery or vanilla JavaScript

As a newcomer to ReactJS, I find myself struggling with using it for more complex tasks. While I grasp the fundamentals, my mind often defaults to jQuery or plain JavaScript when attempting more advanced projects. For example, if I were to create a web a ...

Adding an object array to a new array - Step by step guide

I am working with an array of states const states = [{id:1,name:"New York",cities:[...]},{id:2,name:"California",cities:[...]}] My goal is to extract all cities and store them in a new array using methods ... const cities = [] this.s ...

Having trouble with serving static files on elastic beanstalk

My angular app works perfectly fine on localhost, but on beanstalk it's not serving all my files. Only index.html and styles.css are found and served, both in a folder called public in the root directory. The build file is located at /build/build.js a ...

Having trouble retrieving hidden field value in JavaScript

I am encountering an issue with retrieving hidden field values that were set during page load in the code behind. The problem arises when attempting to access these values in JavaScript, as they are returning as undefined or null. I am unable to retrieve ...

What causes variations in object values when displayed in console.log() compared to when observed in the debugger?

Can anyone explain why the object's variables appear different in the debugger https://i.sstatic.net/l8iKX.png I'm specifically curious about the _id variable, as it seems to be displaying differently! When I check in the debugger, I can't ...

What is the best way to delete a particular tag using jQuery?

Illustration: htmlString = '<font><a>Test Message</a></font>'; updatedHtmlString = htmlString.find('font').remove(); Desired Result: <a>Test Message</a> This code snippet is not yielding the expe ...

The functionality is not operating correctly on Internet Explorer

This code is functioning properly in Mozilla and Opera, but it is not working in IE. Any assistance on this issue would be greatly appreciated. The JavaScript is working fine, however, in IE 10 only the back panel is displayed. Thank you for your help. h ...

sending an array from Javascript to PHP

Utilizing JavaScript, I have successfully converted data from a file into an array. Now, my goal is to utilize input from a form to search through this array using PHP and present the results in a table. Despite browsing various solutions for similar probl ...

Stop form submission with Ajax

I'm currently utilizing a javascript/ajax script to prevent form submission and display messages such as "error!" or "success!". However, it seems that the script is not functioning properly. Instead of preventing the form from submitting, the browser ...

Access and retrieve data from a string using XPath with JavaScript

My HTML page content is stored as a string shown below: <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph.</p> </ ...

Using ES6 classes in Express routes: It is not possible to create the property 'next' on the string '/'

I'm currently working on integrating routes using classes in my express js application controller class User { constructor (){ this.username = 'me'; } getUsername(req,res){ res.json({ 'name& ...

What are some ways to utilize Windows GDI functions in .NET that are not available in GDI+?

I need assistance in accessing a GDI method that seems to be missing in GDI+ within my .NET application. Specifically, I am looking for information on this particular method which retrieves kerning pairs for a specified font. My goal is to incorporate ker ...

A guide to extracting the selected options from a multiple select box and presenting them in a text box

My goal is to have a dropdown menu displaying a list of items, each item corresponding to a specific price. When an item is selected, I want the total price to be automatically calculated and displayed in a textbox. Here is the code for my dropdown menu: ...

Error FWLSE0013E: Unable to call JSONObject procedure due to incompatible casting to JSONArray

I have implemented a client-side function called login in my IBM MobileFirst application, which I found on this informative link. login: function (username,password){ //promise var logindef = $q.defer(); //tempuser ...

Sorting options tailored for arrays within arrays

Here is an array with nested arrays: var array = [ ['201', 'Tom', 'EES', 'California'], ['189', 'Charlie', 'EE', 'New Jersey'], ['245', 'Lisa', ' ...

What is the best way to reload or return to the page after submitting a form?

I am creating a simulated contact form that does not actually send messages. I aim to achieve the effect of refreshing the page upon submitting, giving the appearance that the message has been sent. While my preference is to accomplish this without JavaScr ...