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

The Angular custom modal service is malfunctioning as the component is not getting the necessary updates

As I develop a service in Angular to display components inside a modal, I have encountered an issue. After injecting the component content into the modal and adding it to the page's HTML, the functionality within the component seems to be affected. F ...

Adjust the divs right element by adding or removing 1 pixel for every size change in the browser

I have been exploring different approaches to achieve this task and it seems like using javascript might be the most effective way. I am currently dealing with a stubborn social icon container placement issue. More details on my previous question can be fo ...

No information available at the moment

When the data is not present, it displays as "display none"... However, I want it to show "no data found" This is the current code if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].styl ...

Highcharts real-time data not refreshing following modification of PHP variable

Currently, I have a live updating highchart implemented on a webpage named index.html. This highchart calls a PHP script called datatest.php to parse a CSV file, convert the data into JSON format, and then add it as a new point on the chart: $.ajax({ ...

Tips for creating a cohesive group of HTML elements within an editable area

Imagine having a contenteditable area with some existing content: <div contenteditable="true"> <p>first paragraph</p> <p> <img width='63' src='https://developer.cdn.mozilla.net/media/img/mdn-logo-s ...

AngularJS nested directive with isolated scope for a straightforward implementation

Please take a look at this plunker Despite reading extensively on directives, scopes, and isolated scopes, I am still struggling to comprehend how to make it all work together. The directive I've created functions perfectly on its own, but encounter ...

Angular is having trouble with binding

What seems to be the issue in this code snippet? JSFiddle. function SecondCtrl($scope, Data) { $scope.data = Data; $scope.reversedMessage = function(message) { return message.split("").reverse().join(""); }; } ...

Choose the element before and add a style effect with CSS

I'm trying to create a layout with 3 <div> elements in one horizontal line, each with a width of 33.33%. When hovering over one div, I want its width to expand to 50% while the other two shrink to 25%. <div id="A"></div> <div id= ...

Angular 2 has upgraded its Controller functionality by replacing it with Component

I find it a bit challenging to distinguish between Component and Controller. How was the Controller replaced by component in Angular 2? I came across this description of a component: In Angular, a Component is a distinct type of directive that utilizes a s ...

Angular 2: Navigating through submenu items

I have a question about how to route submenu elements in Angular 2. The structure of my project is as follows: -app ---login ---registration ---mainApp (this is the main part of the app, with a static menu and links) -----subMenu1 (link to some con ...

Does PHP/AJAX only function when an output is generated?

I am attempting to fetch the Wordpress blog header into a php file in order to use it for an AJAX call function. define('WP_USE_THEMES',false); echo 'Something'; require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-b ...

Develop an XML document with the use of either Javascript or PHP

I have an XML file that contains information about bracelets with photo details. <bracelets> <photo filename="b1.jpg" thumbnail="a1.jpg" description="aa" /> <photo filename="b2.jpg" thumbnail="a2.jpg" description="aa" /> & ...

Exploring ways to specifically select predefined strings by defining a regex parameter in angular-ui-router

I need to restrict access to a specific state in my angular-ui-router based on the parameter being one of the following strings: "site1" "site2" "site3" Here is my current state configuration: $stateProvider.state("error", { url: '/error/{sub: ...

Is there a way to simulate the parameters of a method callback from an external dependency in Nodejs

Imagine a scenario where I have the following structure: lib/modules/module1.js var m2 = require('module2'); module.exports = function(){ return { // ... get: function(cb){ m2.someMethod(params, function(error, ...

Retrieving components from Ajax response data

While I have a good grasp of PHP, diving into AJAX and dealing with JSON is proving to be quite challenging for me. My PHP script simply delivers a straightforward JSON string like this: {"bindings": [ {"ircEvent": "PRIVMSG", "method": "newURI", "regex": ...

The outcome of the Javascript Calculator is showing as "Undefined"

I've been attempting to create a calculator using JavaScript, but I'm facing an issue where the 'operate' function keeps returning Undefined, and I can't seem to figure out why. I suspect that the problem lies with the switch state ...

The automated Login Pop Up button appears on its own and does not immediately redirect to the login form

Hey guys, I'm struggling with modifying the jquery and html to ensure that when the login button is clicked, the login form pops up instead of displaying another login button. Another issue I am facing is that the login button seems to pop up automati ...

Detecting letter case and text input in an HTML form can be done by using

I am looking to format a question along with multiple options in a text box, similar to how it is done in a Word file or plain text. Once saved, I want the questions to be displayed in a list and the options organized in a table. How can I extract the ques ...

Looking for assistance with deleting a child element in an XML file using PHP

I need help figuring out how to delete a child from my jobs.xml file with a PHP script. My jobs.xml file looks like this: <jobs> <event jobid="1"> <title>jobtitle</title> <desc>description</desc> &l ...

String includes another String not refreshing automatically

How come myCtrl.greeting doesn't automatically update when I change myCtrl.name? angular.module('MyApp', []) .controller('MainController', [function(){ var mCtrl = this; mCtrl.name = ''; mCt ...