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

Tips on retrieving JavaScript output within an AngularJS model

When I bind the result date to an input text based on the input id, the input value is not saving in the ng model of Angular script. <input type="text" class="form-control" maxlength="10" ng-model="EmployeeSave.HijriDate" onclick="showCal2();" ...

Utilizing jQuery for asynchronous image uploading

Just started learning jQuery and I'm having trouble uploading a jpg image file using the ajax method. It seems like it's not working properly. Can anyone guide me through this process? HTML <form action="" method="POST" enctype="multipart/fo ...

In the absence of a value

In my code, I've implemented a functionality that saves the user's input into local storage and displays it in a specific ID. However, I want to make sure that if the input field is left empty, the user is prompted to enter their name. function ...

Verify if the property in every element of the array is not empty

How can you determine if all employees have a non-null value for the SSN property in the given object? Employees: { id: 0, name: "John", SSN: "1234" } { id: 1, name: "Mark", SSN: "1876" } { id: 2, name: "Sue&q ...

What is the process for implementing the sticky table header jQuery plugin?

I am looking to implement a sticky header on all tables in my web application, which is built on PHP. As the amount of data continues to grow, search results are fetching more records that may not be visible. I am primarily a PHP programmer and do not have ...

Leveraging ES6 modules within JavaScript for exporting uncomplicated variables

In my JavaScript code, I have defined pageId = 3 in one file and socket = io() in another file. Now, I need to access these variables in other files. I am considering using ES6 modules for this purpose, but I am unsure of how to proceed. Currently, the s ...

Looking for a feature where users can easily update their profile using an interactive edit button

I'm currently working on a website project and one of the features I'm tackling is the user's profile page. My objective is to create an edit button within the page that allows the user to modify their name, username, email, and update their ...

Display the retrieved information from MongoDB onto a jade template

Upon checking the console, I see output similar to this: [ { __v: 0, city: 'on1', address: '111', first: 'user', last: 'one', chart: 'char1', doctor: 'doc1', _id: 5698a803d98f05482ba48a4b }, { __ ...

"How to troubleshoot installation errors when installing Angular on Ubuntu using

Hi there, I'm just beginning to dive into learning Angular. However, I've encountered an issue while trying to install Angular using npm install angular on my Ubuntu 16.04LTS system. The error message that pops up is as follows: npm ERR! Linux 4 ...

When a radio button is chosen, multiple text fields must be completed in order to validate the form

I am working with a set of 3 radio buttons. If the last option, labeled "In Home," is chosen, then all 4 of the text fields must be filled in for the form to validate. While I have found information on how to achieve this with checkboxes or a single text f ...

Discover an Easy Way to Scroll to the Bottom of Modal Content with Bootstrap 5 on Your Razor Page

Currently, I am developing a web application that utilizes Razor Pages and Bootstrap 5 modals to showcase dynamic content. The challenge I am facing is ensuring that the content inside the modal automatically scrolls to the bottom when the modal opens or w ...

Tips for swapping out a sticky element as you scroll

Context As I work on developing a blog website, I aim to integrate a sticky element that dynamically updates according to the current year and month as users scroll through the content. This would provide a visual indication of the timeline for the listed ...

Ways to retrieve information from a intricate JSON structure?

Can anyone help me understand why I am unable to access the data in the detail option of the JSON? My goal is to load the firstName, lastName, and age into a list for each object. var data = { "events": [{ "date": "one", "event": "", "info ...

How can React and Redux ensure that response data is accessible to every component?

When using react and redux, how can data written in the useDispatch function be made available in other components? Additionally, how can the customerId be accessed in all components? I have created a code that calls an API and returns data in response. I ...

What is the process for sending body data through Swagger in a Node.js/Express environment?

Below is the configuration for my swagger: /** * @swagger * /api/addData: * post: * consumes: * - text/html * produces: * - text/html * parameters: * - name: author * in: body * required: true * ...

How can the Header of a get-request for an npm module be modified?

Currently, I am utilizing an npm module to perform an API request: const api_req = require('my-npm-module-that-makes-an-api-request'); However, I am seeking a way to modify the user-agent used for requests generated internally by the npm module ...

A function with a specific name for sorting a multidimensional object based on a specified sub-key's value, without anonymity

My data consists of a collection of objects, not an array: var people = {}; people['Zanny'] = {date: 447, last: 'Smith'}; people['Nancy'] = {date: 947, last: 'William'}; people['Jen'] = {date: 147, last: &a ...

Adding elements to a JSON array in JavaScript/AngularJS

Looking for help with inserting a new item "uid" into a JSON array. Here is the initial array: var testArr=[{name:"name1",age:20},{name:"name1",age:20},{name:"name1",age:20}] The desired output after inserting the "uid" would be: var testArr=[{name:"nam ...

Tips for preventing a NodeJS script from crashing due to timeout being exceeded

Here is the issue I am encountering: I am attempting to scrape a website's content using NodeJS and puppeteer. Sometimes, my code halts with a Timeout Exceeded error. Is there a way for me to handle this timeout by implementing a function that will e ...

Is there a way to utilize regular expressions in React to dynamically insert onclick events into specific words within a text block?

I've been experimenting with regular expressions in React to implement an onclick event for each word in a text. I've attempted two different strategies, but neither has been successful thus far. Initially, I tried: return( <div> & ...