Differentiating the angular distinction between setting a variable with ng-click and invoking a function

I've encountered a situation like this before.

Let's assume the controller has these variables:

$scope.valueArr = ['Hello', 'No', 'Yes'];
$scope.myValue = 'Hello';

And there is an ng-repeat as follows:

<li ng-repeat="value in valueArr" ng-class="{'active' :  myValue == value}"><a>{{value}}</a> </li>

If I do this:

<a ng-click="myValue = value"> </a>

The new element gets the class, but the previous one loses it.

However, if I try this instead:

<a ng-click="setMyValue(value);"> </a>

and define the function in the controller:

$scope.setMyValue = function(value){$scope.myValue = value}

Only the last clicked element stays active, showing that a function is necessary for re-rendering. Can someone explain why this happens and when to use each method?

This case is just one example where re-rendering issues come up.

Answer №1

One reason for this behavior is that when using ng-repeat, a new child scope is created for each repetition, as explained in the documentation.

This means that each repeated item has its own separate scope.

There is a distinct child scope for the first repetition.

There is a distinctive child scope for the second repetition.

There is a unique child scope for the third repetition.

...and so on.

Therefore, if you try to access a variable like (myValue) using

ng-click="myValue = value"
, Angular will search within the current repetition's child scope. If it doesn't find any existing reference to myValue, it will create one within that specific child scope. However, you can still access variables from the parent scope by using syntax like $parent.myValue.

You can test this behavior with the following demo.


Another approach to handle this situation is to use an object, for example:

$scope.tempObj = {myValue: 'Hello'};

Then, you can refer to this object property by using:

<a ng-click="tempObj.myValue = value">

Since myValue is now a property of the object tempObj, if Angular cannot find tempObj in the child scope, it will automatically look through the parent scopes.


If you opt to use a function like:

<a ng-click="setMyValue(value);"> </a>

&

$scope.setMyValue = function(value){$scope.myValue = value}

In the setMyValue function, it accesses $scope.myValue from the controller scope directly, rather than relying on the repeat's child scope.

Answer №2

The use of ng-repeat results in the creation of a distinct child scope for each repeated element. For instance, when you input

<a ng-click="myValue = value"> </a>

What occurs is the generation of a new variable 'myValue' within the child scope of the <li> after the user triggers the button. This action conceals the original value of 'myValue' within the parent scope without altering it - effectively causing all other <li> scopes to continue inheriting the original value from the parent scope.

On the contrary, if you were to write

<a ng-click="setMyValue(value);"> </a>

You would be directly invoking the function setMyValue that was established within the parent scope. Consequently, when the button is clicked, the setMyValue function executes and modifies the 'myValue' attribute within the parent scope. The child scope remains unaffected by this adjustment. With the alteration occurring within the parent scope, all instances of <li> elements inherit the updated value accordingly.

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

Refine results by searching through the text contained in the elements of every div

I recently came across a helpful fiddle that allows text to be hidden based on what is entered into a search box. However, I am struggling to apply this method to a div that contains multiple elements. Is there a way to modify the jQuery in the provided fi ...

What could be causing the malfunction of this Bootstrap button dropdown?

Initially, I attempted using regular HTML for the dropdown button but encountered issues. As a result, I switched to jsfiddle to troubleshoot. Despite my efforts, the dropdown feature still refused to work. If you'd like to take a closer look, here&a ...

There seems to be a mysterious absence of chuck norris jokes in

I'm attempting to call two different APIs by clicking a button to display a random joke on the screen. I've created two separate functions to fetch the APIs and used Math.random() to generate a random number. If the number is greater than 50, one ...

Which is the best framework to transform a NextJS website into a desktop application: Electron, React-Native, or React-

After recently mastering ReactJS, I am currently utilizing it to create an application with NextJS. My goal is to make this application available as a desktop version as well. I have been introduced to Electron, React-Native, and React-Desktop, but I am u ...

How can we replicate user input in React for unit testing purposes?

Struggling to unit test a React component that accepts user input, specifically the onChange function within the component. Unable to set the input value despite trying various methods found online. Below is the component under test: class Input extends C ...

Using jQuery to remove the functionality of a file input button is ineffective

I am having trouble with an input type file element: <input type="file" name="val1" /> And I'm using this jQuery code: $("input[name='val1']").off("click"); However, the above script, which is already included in a $(function() { } ...

Encountered an issue with trying to access the 'map' property of an undefined value while using Express and VueJS

Currently, I am in the process of developing a fullstack application utilizing Express, VueJS, and Mongoose. The app functions as a news feed platform. A couple of days ago, I encountered an error which was resolved with the help of your guidance. However, ...

Utilize a variable within an HTML attribute

Currently utilizing Angular and I have the following HTML snippet <input onKeyDown="if(this.value.length==12 && event.keyCode!=8) return false;"/> Is there a way for me to incorporate the variable "myNum" instead of the ...

I currently have an array of strings and wish to print only the lines that include a specific substring

Here i want to showcase lines that contain the following strings: Object.< anonymous > These are multiple lines: Discover those lines that have the substring Object . < anonymous > Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'you ...

Utilize JavaScript to extract and exhibit various SQL records stored within a multidimensional array

How can I use JS, JQuery, PHP, and MySQLi to automatically generate an HTML table within a div on a webpage? The table should display data based on user-input search criteria. For example, the user enters a start date and end date, clicks a button, which t ...

JavaScript: Efficiently Sorting a Multidimensional Array

Here is the array that needs to be sorted based on the third item: const array = [ [1, "Convention Hall", "Mumbai", 10, "XYZ Company"], [2, "Auditorium", "Delhi", 10, "ABC Company"], [3, "CenterHall", "Bangalore", 10, "ZZZ Company"], ... ...

When the field is clicked into for the second time, the month and year picker values will update

I recently implemented a month and year date picker code I found on a website. While I was able to customize the date format (mm/dd/yy) and successfully select values, I encountered an issue where the selected date changes drastically when clicking away fr ...

Do you require assistance with creating an image slideshow?

My first day working with HTML was a success as I successfully built a navigation bar that looks pretty cool. Take a look at it here. Next on my list is to incorporate a slideshow into my site, possibly using JavaScript or jQuery plugins. I'm aiming ...

What is the best way to convert a List of objects to JSON using a dynamic variable?

I have a need to serialize a list of objects in a specific way: Imagine I have the following C# class: public class Test { public string Key; public string Value; } List<Test> tests; When I serialize this list (return Json(tests.ToArray()) ...

The simplest method to make HTML elements inaccessible to the Simple HTML Dom Parser in PHP

Imagine a scenario where a basic web application is running and utilizing Simple HTML Dom Parser. The code snippet below demonstrates this: <?php include('simple_html_dom.php'); $html = file_get_html('http://someurl.com'); ...

Develop a cutting-edge application by integrating ASP.NET MVC Areas with an innovative Angular

How can AngularJS be integrated with Asp.net MVC "Areas"? I am currently working on a project that involves a large user base and extensive database tables (approximately 5 million rows for 8 to 10 tables). To handle data manipulation and UI, I have decid ...

Guide to making a JavaScript button that triggers an iframe to open upon user clicking the button

I'm currently enhancing the comment section for posts on my website. I am looking to implement a button in javascript that, when clicked, will open an iframe window displaying comments similar to how Facebook does on their post. If there are other lan ...

JQuery may be successfully loaded, but it is not functioning as intended

Just started dabbling in JQuery (I'm a newbie) but I'm having trouble getting it to work! Initially, it worked a couple of times but then suddenly stopped working (pretty strange). I made some changes and now it doesn't work at all. JQuery a ...

Bug in canvas rendering for Chrome versions 94 and 95

The Canvas drawing functionality in the Chrome browser seems to have some visible bugs. Here's an example of code that demonstrates this issue: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d&apo ...

What is preventing WebRTC from re-establishing connection after being disconnected?

In my current React web application project, I am implementing a feature where users can engage in group calls using WebRTC through a NodeJS server running Socket.IO. The setup allows for seamless joining and leaving of the call, similar to platforms like ...