Sending Javascript variable to AngularJS

I'm a beginner in the world of AngularJS and JavaScript, and I'm struggling to figure out how to pass a JavaScript variable into my AngularJS controller. Here's the snippet from my html page:

 <!DOCTYPE html>

        <html lang = "en" xmlns="http://www.w3.org/1999/xhtml" ng-app="test">
        <head>
            <meta charset="utf-8" />
            <title>Test</title>
            <!--Third party scripts-->
            <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
            <script type="text/javascript" src="js/angular.min.js"></script>
            <script type="text/javascript" src="js/angular-sanitize.min.js"></script>
            <!--Custom scripts-->
            <script type=" text/javascript" src="app/test.js"></script>
            <!--Third party style sheets-->
            <link type="text/css" rel="stylesheet" href="css/test.css" />
        </head>
        <body>

        <div id="page" ng-controller="PageCtrl">
            <ul>
                <li ng-click="print(gBool)"><a href="#print">Print</a></li>
            </ul>
        </div>
        </body>
        </html>
        <script>
            var gBool = false;
            window.onload = function () {
                gBool = true;
            };
        </script>
    

This is the AngularJS code I have:

var app = angular.module('test', []);

        app.controller('PageCtrl', ['$scope', function ($scope) {
            $scope.print = function (boolParam) {
                    console.log(boolParam);
            };
        }]);
    

When this runs, it only shows 'undefined' in the console. Shouldn't this be working?

Answer №1

It's essential to follow the "angular" approach and utilize $window:

let myApp = angular.module('myapp', []);

myApp.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.userId = $window.userId;
}]);

Answer №2

Within this segment:

<li ng-click="print(gBool)"><a href="#print">Print</a></li>

You are making use of a variable called gBool in your scope, so its $scope.gBool. If you declare it in your JavaScript rather than in your HTML, it will function properly.

$scope.gBool = true;

Moreover, look into $window and incorporate it in your controller like so:

app.controller('PageCtrl', ['$scope', '$window', function ($scope, '$window') {
    $scope.gBool = false;
    $window.onload = function() {
        $scope.gBool = true;
    };
    $scope.print = function (boolParam) {
            console.log(boolParam);
    };
}]);

Answer №3

Focus on two key aspects:

(i) Make sure to initialize the variables using ng-init (ii) Create a function to set the initial boolean value

Check out this Application for a demonstration.

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

How to place a stylish font over an image and recreate hover effects

I am looking to place social media icons below an image next to the photo's title, including Facebook, Twitter, Soundcloud, and Instagram. I want these icons to rotate along with the image when it is hovered over. HTML <div class="polaroid-image ...

JavaScript transforming an array into a counter

I am seeking a way to transform a one-dimensional array into a frequency dictionary in JavaScript. The array elements should serve as keys, while their frequencies act as values. Take, for example, the Python script below, which generate a list of 1024 ra ...

The impact of placing a method in the constructor versus outside it within a class (yielding identical outcomes)

These two code snippets appear to produce the same result. However, I am curious about the differences between the two approaches and when it would be more appropriate to use one over the other. Can someone provide insight into this matter? Snippet 1: c ...

Using animate.css and jQuery for sequential animations

Is there a way to make them fadeInUp one after the other? Check out the demo http://jsfiddle.net/uz2rm8jy/4/ Here is the HTML structure: <div class="c one"></div> <div class="c two"></div> <div class="c three"></div> ...

servlet failing to send a response to ajax call

I am facing an issue where the servlet is not sending back a response to my AJAX code. Can someone please help me with this? Below is the HTML code, the output should be printed here: This is the AJAX code written in JavaScript: <script language="jav ...

Communicating PHP variables with JavaScript through AJAX in a chat application

Hello there! I am currently in the process of developing a chat application for my website that includes user registration and login. My backend server is built using NodeJS to leverage SocketIO capabilities. Within my index.php file, I have implemented ...

Facing an issue in React-Native where unable to navigate to the second screen

I hope you don't mind the length of my query, as this happens to be my debut here and I am really eager to unravel the mysteries surrounding my code conundrum. Your assistance in this matter would be greatly appreciated. Could someone please lend me ...

What is the best way to dynamically reference an HTML file based on the value of a JSON data description, using the description as the filename

Here I have created a sample file which is currently working fine. However, my requirement is to call the HTML elements from a separate file and only reference the external file name in the Description field. Is it possible to achieve this by specifying th ...

Selected value is not displayed in the textbox when using autocomplete feature

---Ajax---- An issue has arisen with the autocomplete feature. While typing "wi" (for example, wipro), the drop-down list appears as expected. However, if only "wi" is selected in the text box, $(document).ready(function () { $("#company_name").key ...

Exploring Jasmine and Karma for testing Angular 5 HTTP requests and responses

I am brand new to the concept of Test-Driven Development (TDD) and I am currently in the process of debugging a complex Angular 5 application for the company I work for. The application is functioning without any issues, but now I need to incorporate test ...

Using jQuery UI datepicker - how to set a parameter based on a specific condition

New to the world of JavaScript, I am trying my hand at implementing the jQuery UI datepicker widget. My goal is to add an additional line to the widget parameters if the variable selectedDate has a value. However, my current approach seems to be ineffecti ...

Sending a blob through AJAX to a different domain using CORS

Could someone please explain why my current request is being blocked by the SO policy restriction? Javascript Code: var blob = new Blob([req.response], {type: "application/octet-stream"}); req = new XMLHttpRequest(); req.open("POST", ws_path(other_contex ...

React JS's popup feature can be unreliable, as it tends to break the application frequently

I have been developing a web application that interacts with a public API and presents the retrieved data in a table format. However, I am encountering an issue where clicking the "Click to Display Hottest Planet" button sometimes results in an error. How ...

Unlocking the Secrets of AnimatedInterpolation Values

I have a question about how to access the value of an AnimatedInterpolation in react-native without resorting to calling private code. To achieve this, I first create an animated value and then wrap it in an interpolation like so: animated = new Anima ...

Vue datatable button event malfunctioning

I'm currently working with the Vue.js datatable. Most functionalities are operational, however, I am facing an issue where the `callmethod()` is not being executed upon clicking a button. When the button is clicked, no events seem to be triggered. Any ...

Having trouble setting up an input tag to successfully submit the form and trigger the opening of a BootStrap Modal

Is there a way for me to submit a form to my servlet and open a BootStrap Modal simultaneously using an input tag in my .jsp file? I've tried setting the input tag type to "button" but then I can't submit the form. And when I set it to "submit", ...

Remove a comment from the page without needing to refresh the entire

Is there a way to enhance this code so that when a comment is deleted, the page does not refresh? It can be frustrating when deleting a comment causes the page to scroll back to the top. AJAX function deleteComment(pid){ $.ajax({ type: "PO ...

Tips for executing a script on the "body" using "body onload=myfunc()" in an ASP.NET content page

I have included my script "myscript.js" in the master page. Now, in a content page, I want to load myscript() on startup (body onload). Is there a way to accomplish this? ...

What is causing the data added to an array to vanish after the forEach loop within the useEffect hooks?

Below is the code snippet: const Tabs = ({data, scrollX}) => { const [measures, setMeasures] = useState([]); const containerRef = useRef({}); let measureMentArray = []; useEffect(() => { data && data.forEach(item => { ...

Retrieve the highest 10 values from a JSON document using jQuery

I am working with a JSON file in my jQuery project, and I need to display only the top 10 values with the highest numbers. For instance: JSON: { "value": { "number": "12", "number": "11", "number": "10", "number": "9", "number": "8", ...