I am attempting to access an Angular variable using JavaScript, but unfortunately, I am encountering some issues

I'm currently implementing the following code:

window.onload=function(){
    var dom_el2 = document.querySelector('[ng-controller="myCtrl"]');
    var ng_el2 = angular.element(dom_el2);
    var ng_el_scope2 = ng_el2.scope();
    console.log(ng_el_scope2);
    var datan3 = ng_el_scope2.itson;
    console.log(datan3);
      }

However, it consistently displays the value of itson as undefined. I've experimented with various methods but have yet to find a satisfactory solution. Any recommendations for effectively accessing an Angular variable from JavaScript without resorting to $window?

Answer №1

@MikeMcCaughan makes a valid point, it's definitely not the best practice! However, if you find yourself in a situation where you absolutely must do it, here's a straightforward example showcasing how to achieve this using a controller and Vanilla JS for accessing its variables and functions externally.

index.html

<!doctype html>

<html lang="en" ng-app="app">
<head>
  <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
  <script src="script.js"></script>
</head>

<body>
    <div id="myController" ng-controller="myController as vm">
        My name is {{vm.fullName}}
    </div>
    <br>
    <button onclick="accessControllerScopeVar()">Get full name</button>  
    <button onclick="accessControllerScopeFunction()">Say hello !</button>   
</body>
</html>

script.js

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

angular
.module('app')
.controller('myController', ['$scope', function ($scope) {

    var vm = this;

    vm.fullName = 'Marty McFly';

    vm.getFullName = function() {
        return vm.fullName;
    }

}]);

function accessControllerScopeVar() {
    var scope = getScopeFor("myController");
    scope.$apply(function () {
        alert(scope.vm.fullName);
    });
}

function accessControllerScopeFunction() {
    var scope = getScopeFor("myController");
    scope.$apply(function () {
        alert('Hello ' + scope.vm.getFullName());
    });
}

function getScopeFor(id) {
    var el = document.getElementById(id);
    var scope = angular.element(el).scope();
    return scope;
}

Check out the Plunker for a live demo: https://plnkr.co/edit/7U78a6Xdlaef2qOgwucC?p=preview

Another Approach

In case you prefer not to use ids, here's an alternative method utilizing document.querySelector:

https://plnkr.co/edit/AtAoJhU9zUhYZLC5US5Y?p=preview

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

Building a custom Vuetify extension to enhance core features

I am currently working on developing a plugin-based component library to ensure consistency across various product lines using vuetify. However, when I try to install the library and add the components, I encounter multiple errors related to the dark theme ...

Troubleshooting problems with callback functionality in conjunction with Expressjs, JWT authentication, and Angular

For my current project, I am implementing authentication using JWT with Expressjs and Angularjs. However, I now need to integrate node-dbox to access Dropbox files of my users. The issue arises when trying to store the token received from Dropbox for user ...

Transforming Arrays of Objects into a Single Object (Using ES6 Syntax)

My attempt to create aesthetically pleasing Objects of arrays resulted in something unexpected. { "label": [ "Instagram" ], "value": [ "@username" ] } How can I transform it into the d ...

Controller encountering JSON null data

I am currently working on a feature that allows users to send multiple email/SMS messages by selecting checkboxes. However, I am facing an issue where the data is not being passed correctly from my JavaScript function to the action method - all the data sh ...

Creating a JSX.Element as a prop within a TypeScript interface

I need to create an interface for a component that will accept a JSX.Element as a prop. I have been using ReactNode for this purpose, but I am facing issues when trying to display the icon. How can I resolve this issue? export interface firstLevelMenuItem ...

What is the reason behind the NgForOf directive in Angular not supporting union types?

Within my component, I have defined a property array as follows: array: number[] | string[] = ['1', '2']; In the template, I am using ngFor to iterate over the elements of this array: <div *ngFor="let element of array"> ...

Validate all JavaScript buttons by binding a click event

I've implemented the JS validation plugin from this source and it's functioning properly. However, it captures all button clicks on the page, including when I click on Back to Home, triggering form validation unnecessarily. I only want the form ...

Error encountered while adding x-ray-scraper to project using Npm

I am currently working on a Vue application and utilizing the x-ray-scraper library. However, when I attempt to run npm run serve in the terminal to preview the application locally, I encounter the following error: This dependency was not found: * _http_c ...

Is it possible to trigger a re-render of a child component from its parent component in React without altering its props?

The issue at hand My parent component (X) is responsible for managing numerous states and child components. Within these children, there is an animated component (Y) - an avatar with various facial expressions that change in sync with its dialogue. Curr ...

Having trouble retrieving the ID of the clicked element in AngularJS?

I have successfully implemented a function in angularjs to retrieve the id of the clicked element. Below is my code snippet html <a href="#faqinner/contactform" class="clearfix" ng-click="getCateId($event)" id="{{option.id}}"> <span class= ...

What are some ways to track the loading progress of a JSON file retrieved through an Axios call?

To track progress accurately, I am contemplating implementing the following steps while making an axios call: Retrieve file size during the json file request Determine the percentage of downloaded file size from the network tab Currently, I only have a ...

Interactive image popups with JavaScript

Seeking assistance in generating a popup when selecting an area on an image map using Javascript. As a novice in JS, I have successfully implemented popups for buttons before but encountered issues with this code within the image map - the popup appears br ...

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 ...

Here's a new take on the topic: "Implementing image change functionality for a specific div in Angular 8 using data from a loop"

I need to create a list with dynamic data using a loop. When I click on any item in the list, I want the image associated with that item to change to a second image (dummyimage.com/300.png/09f/fff) to indicate it's active. This change should persist e ...

Make the background disappear when the text field is left empty and the cursor is not present (onUnfocus)

When the text field is empty and there is no cursor in the text field, I want it to be transparent and for the spell checker not working. The result should be displayed a little to the left inside a <div>. Should this be done using CSS, JavaScript, ...

Implementing Placeholder Text Across Multiple Lines with Material UI

Currently, for the React App I am developing, I am utilizing Material UI. In order to achieve a multi-line placeholder for a textarea using the TextField component, here is what I have so far: <TextField id="details" ful ...

What is the most efficient method for managing components with dynamic templates and their corresponding data in Vue.js?

I have a question and requirement that I would like to discuss. It involves dynamically rendering templates and data using components. The scenario is as follows: The root Vue instance fetches data from the backend, and let's say the following data i ...

The unexpected occurence of the Onbeforeunload exception

I am attempting to create an exception for onbeforeunload and display a warning about potential data loss whenever the quantity is not zero: Here is what I have tried so far: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...

Struggling to capture an error generated by Sequelize within a universal Middleware block

In a test project, I have successfully implemented CLS transaction control in Sequelize using 'cls-hooked'. The transactions work seamlessly both in the command line and with Express. They are injected and managed automatically, rolling back on a ...

Encountering a parsing failure in the _app.js file of a new Next.js project: Unexpected token

When starting a new Next.js project, I use the following command: npx create-next-app After moving into the project folder and running npm run dev, I encounter the following error: C:/Users/mikke/Documents/Projects/next-project/pages/_app.js 4:9 Module pa ...