Controller Function Utilizing Private Variable in AngularJS

After stumbling upon an Angularjs example online, I found myself perplexed. The code snippet in question is as follows:

angular.module("testApp",[]).controller("testCtrl", function($scope){

    var data = "Hello";

    $scope.getData = function(){
        return data;
    }

    $scope.setData = function(newData){
        data = newData;
    }
});

The corresponding view is outlined below:

<html ng-app = "testApp">
    <head>
        <script src="lib/Angular.js"></script>
        <script src = "foo.js"></script>
    </head>
    <body ng-controller="testCtrl">
        <div ng-click="setData('Hello Hello')">{{getData()}}</div>
    </body>
</html>

My inquiry revolves around how Angular triggers the getData() method within the view. Since the click event modifies a private variable that isn't attached to $scope, and therefore not being watched for changes, how does Angular know when to call getData() in the view? I understand this may seem like a basic question, but any guidance would be greatly appreciated. Thank you!

Answer №1

AngularJS refers to the double-curly expression as an observing directive. During compilation, this directive sets up listeners on the expression using the $watch method of the scope.

In contrast, ng-click is known in AngularJS as a listener directive. This directive attaches a listener to the DOM instead. Whenever the DOM event occurs, the directive triggers the associated expression within an $apply call.

After executing the click expression, a $digest cycle initiates. During this cycle, the scope reviews all registered $watch expressions (such as the double-curly expression with getData()) and invokes the listener if there is any change from the previous value.

Ultimately, it is this digest cycle that guarantees the evaluation of all your bound expressions.

Answer №2

Before rendering the view, the top-level controller function is executed to initialize the scope. As the view loads, any logic within it is carried out. When getData() is reached, it will return the output of that function at that particular moment.

An interesting aspect is that Angular automatically connects the data in your views back to the data model, enabling any changes made in the model to reflect in the view. This means that if there is a modification in the source of the data, the value in the view will be updated accordingly and getData() may run multiple times if needed.

I have stored it here on Plnkr

Answer №3

The binding {{fetchData()}} is considered a "run-on evaluation". This means that when the DOM renders and Angular processes it, the parentheses at the end prompt the function to be executed. I will include a proper citation shortly once I locate it.

Answer №4

In the context of AngularJS, utilizing the getData function may not be necessary for the specific demonstration at hand or could serve other purposes.

To achieve the intended functionality without using getData, the revised code would look like this:

    <html ng-app = "testApp">
    <head>
        <script src="lib/Angular.js"></script>
        <script src = "foo.js"></script>
    </head>
    <body ng-controller="testCtrl">
        <div ng-click="setData('Hello Hello')">{{data}}</div>
    </body>
</html>

If including the getData function, the updated code block would be:

    $scope.getData = function(){
        data = 'Hello World';
    }

<html ng-app = "testApp">
    <head>
        <script src="lib/Angular.js"></script>
        <script src = "foo.js"></script>
    </head>
    <body ng-controller="testCtrl">
        <div ng-init="getData()" ng-click="setData('Hello Hello')">{{data}}</div>
    </body>
</html>

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

Troubleshooting JQuery AJAX HTML Problems in Google Chrome and Firefox

I'm facing an issue with my code and I'm not sure what to do. It works perfectly on Internet Explorer, but when I try to open it on Chrome or Mozilla, the links in my menu don't work! I click on them but nothing happens. Can someone please h ...

Is it normal for Tailwind animation to loop twice when transitioning between pages in Next.js?

I'm currently utilizing react-hot-toast for displaying alerts and animating them during page transitions. The animation involves a double fade-in effect when transitioning between pages. In my project, I've integrated tailwindcss-animate within ...

What could be causing this program to continuously add values to the message table whenever the page is refreshed?

Looking for a simple chatting system using php, mysql, html, css and javascript? Check out this code snippet. However, there seems to be an issue with the message sending functionality. Every time a user sends a message and refreshes the page, the same m ...

Guidelines for filling an Express handlebars template and sending it via email

I am currently utilizing node.js, express, express-handlebars, and nodemailer for my project. My objective is to populate an HBS template with content and style it as an email before sending it out. The end result can be viewed below (first rendered in the ...

Leveraging the power of JavaScript's .map(...) method in a

Within my React code, I have a structure similar to the following: {elements.map((element) => { return ( <div> {renderDate(element.date)} </div> ) }})} This structure calls the renderDate function defined as: co ...

Showing canvas lines while dragging (using only plain JavaScript, with React.JS if needed)

Is there a way to add lines with two clicks and have them visible while moving the mouse? The line should only be drawn when clicking the left mouse button. Any suggestions on how I can modify my code to achieve this functionality? Currently, the lines are ...

Is there a way to duplicate an image a specified number of times depending on a given output value?

As a beginner in coding, I am looking to learn how to dynamically insert multiple images based on input and output values. Currently, my code for basic addition looks like this: <form oninput="x.value=parseInt(a.value)+parseInt(b.value)"> <inpu ...

Changing the background color of the dropdown button in Vue Bootstrap: A step-by-step guide

I've been struggling to modify the background color of a dropdown button, but no method seems to work. I've attempted changing it by using ID, removing its class and applying a new one, and even using !important to override the styles, but the ba ...

When utilizing the map function with an array containing 168 objects in the state of a React application, a freeze of around 1

I encountered an issue when trying to update a property in a state array of objects after executing an axios.put request. Here is my code: States - useEffect //... const [volunteers, setVolunteers] = useState([]); //... useEffect(() => { async fu ...

Unable to retrieve Objects from JSON

Here is a JSON object I received: [{"model": "pricing.cashflow", "pk": 1, "fields": {"value": 4.0, "date": "2016-09-09"}}, {"model": "pricing.cashflow", "pk": 2, "fields": {"value": 3.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 3, "fiel ...

Express causing textarea in http form to have empty req.body

Here is a form for users to upload a file and submit text: form(action='/createpost' enctype="multipart/form-data" method='post' id="imgForm") input(type='file' name='imgPath' size = "60") br textarea(na ...

"Struggling to make the 'overflow: hidden' property work for an absolutely positioned

I'm struggling to conceal an absolutely positioned image within a CSS grid layout. Below is the code snippet: HTML: <div class="relative-parent"> <div v-for="item in 12" class="hiding-parent"> <div c ...

Incorporating PHP variables within JavaScript

As a beginner in web development, I am working on creating an application that heavily relies on JavaScript but also includes PHP/MySQL to prevent users from viewing quiz answers by inspecting the page source. The key pages involved in this project are: in ...

What is the standard practice in AJAX for determining a specific state during page loading?

Since I started diving into the world of serious ajax operations, one question has been on my mind. Let me illustrate with an example. Imagine fetching a standard HTML page for a customer from the server. The URL could look like this: /myapp/customer/54 ...

Choose information based on the prior choice made

Using the Material UI Stepper, I have a task that involves setting conditions based on the selection of checkboxes. In step one, there are two checkboxes - Individual and Bulk. In step two, there are also two checkboxes - First Screening and Second Screeni ...

Instructions on extracting a JWT token from an external API for user authentication, followed by saving the user's name and email address into the database

After researching numerous articles and Stack Overflow questions, I have identified my problem and outlined my requirements below: Upon accessing the Angular application, I require immediate user authentication to retrieve their name and email. This auth ...

Is using setTimeout in a group of promises blocking in JavaScript?

Is it possible for multiple requests to be queued up and executed in sequence when calling the function func? The third promise within func includes a lengthy setTimeout that can run for as long as 3 days. Will additional calls to func trigger one after an ...

Issue with CornerstoneJs React restoreImageIdToolState causing annotations to fail to load automatically post-execution

Once this code is executed, I need the annotations to appear without having to hover over the cornerstoneViewport. const restore = () => { let element; const stack = { currentImageIdIndex: 0, imageIds, }; console.log(dico ...

Synchronous async routes in Node Express

My express server requires fetching data from multiple external sources for each request, with the logic separated into various routers (some of which are not under my control). These routers operate independently, eliminating the need for one to wait on ...

Focusing in on the mouse location to magnify a THREE.js element

I am currently working on a project using THREE.js and I have encountered an issue with zooming the object. The zoom functionality is centered around the render position when using trackball controls, but I need it to be based on the cursor's position ...