What is preventing ng-click from assigning a variable with the value from ng-repeat in AngularJS?

I'm currently working on a feature for an app that allows users to select font styles from Google Fonts for specific text elements.

Here's the code snippet I have so far:

<ul ng-init='headerFont="mono"'>
  <li ng-repeat='font in fonts' style='font-family: {{font}};' ng-click='headerFont = font'>{{font}}
  </li>
</ul>

Later on, I use this code to display the selected font:

<h1 style='font-family: {{headerFont}};'>Header</h1>

In my JavaScript controller file, I define the list of available fonts like this:

$scope.fonts = [...an array of font names...]

Initially, instead of using ng-repeat with <li>, I had a different approach:

<select ng-model='headerFont' style='font-family: {{headerFont}};'>
  <option ng-repeat='font in fonts' style='font-family:{{font}};'>{{font}}
  </option>
</select>

This method worked perfectly as expected. However, I decided to switch to a scrollable list rather than a dropdown menu because the <select> element doesn't allow changing individual font styles within options on mobile browsers. It was essential for users to preview fonts before making a selection. Although I attempted to update the font selection using ng-click to set the headerFont value, it seems not to be functioning (no errors are displayed in the console either). Can someone provide insight into why this might be happening?

Answer №1

The issue lies in ngRepeat generating a child scope for each iteration, causing ngClick to modify the local child variable headerFont.

An effective workaround is to explicitly access the parent scope:

var application = angular.module('demonstration', []);
application.controller('demoController', function($controlScope) {
    $controlScope.fonts = ['Arial', 'Times New Roman', 'Verdana', 'mono'];
})
<script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f998979e8c95988bd7938ab9c8d7cdd781">[email protected]</a>" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>

<div ng-app="demonstration" ng-controller="demoController">
    <h1 style='font-family: {{headerFont}};'>Header</h1>

    <ul ng-init='headerFont="mono"'>
        <li ng-repeat='style in fonts' style='font-family: {{style}};' ng-click='$root.headerFont = style'>{{style}}</li>
    </ul>
</div>

Answer №2

Every time ng-repeat is used, a new scope is created. The function of ng-click is to change the headerFont within its own scope, without affecting the headerFont at the highest level.

To prevent the child scope from taking over, you can create a dictionary at the highest level:

<ul ng-init="top = {'headerFont':'mono'}">
 <li ng-repeat='font in fonts' 
     style='font-family: {{font}};' 
     ng-click='top.headerFont = font'>
   {{font}} / {{top.headerFont}}
  </li>
</ul>

Demo: http://plnkr.co/edit/77zesZsBgYpZUDWciY18?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

Struggling to receive accurate data from every statement

I have an object (known as allUserInfo) that looks like this: Object { available_client_ids: Array[2] 0: "demo" 1: "4532t78" available_client_names: Array[2] 0: "Demo" 1: "Bobs Bakery" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Modify the classname of two element class i

I am trying to change the class on click within an <i> element that has 2 classes. The first class is always "fa" and the second class can be either "fa-minus" or "fa-plus". I need to toggle between "minus" and "plus" based on the current class. Ca ...

Deactivate a setInterval function within a Vue.js component

I am facing an issue in my VUE SPA where I have a component running a recursive countdown using setInterval functions. The problem is that the countdown continues running in the background even when I switch to another view, but I want to destroy the setIn ...

How can I add text to a textbox within a duplicated div using Javascript or Jquery?

I'm looking to add text to a cloned div's text box using jQuery. I have a div with a button and text box, and by cloning it, I want to dynamically insert text into the new div. $(document).ready(function () { $("#click").click(function () { ...

Having trouble accessing portlet resource URL from JavaScript in Liferay 6.2

I have been working with Liferay Portal 6.2 CE GA3 and I am facing an issue where I need to execute a custom portlet resource method from another portlet's JSP file. Below is the code snippet I am currently using. <a href ="#" onclick="myfunctio ...

Using ThreeJS to project a texture onto a mesh surface

I am trying to project a texture onto the surface of a mesh using ThreeJS. The link provided achieves the desired result, although I am uncertain about the method used to accomplish it. . As I continue my research, I will update this post. If anyone has ...

Unprepared for handling JSON data with JavaScript and jQuery

{ "Items": [ { "location": "bakery", "item1": "milk", "item2": "bread" } ], } Currently, I am encountering difficulties in parsing a JSON object and receiving the following error: Error: Unca ...

socket.io initialization and finalization events

Currently, I am integrating socket.io with express 3 for my application development. I am interested in implementing loader animations that will appear when a message is incoming and disappear once the message has been received. Similar to how jQuery&apos ...

Retrieve a form (for verification purposes) from a separate AngularJS component

I'm facing an issue with accessing a form from one component to another in my project. One component contains a form, and the other has navigation buttons that, when clicked, should validate the form before moving on to the next step. However, I alway ...

Exploring JSON data to extract values

I am facing difficulty parsing a complex array of JSON, specifically extracting the values "1238630400000" and "16.10". I need to extract all values from this JSON but I am unsure how to do it. Here is the code I have attempted so far: for (var key in my ...

Encountered an issue while trying to send an email through the Gmail API: Unfortunately, this API does not provide

I am attempting to use the Gmail API to send emails. I collect user data and convert it to a base64url string. After obtaining the raw value, I attempt to send the email using a POST request. var ss=new Buffer(message).toString('base64') var ...

Spinning text within a circular rotation in CSS

Looking for guidance on how to center the "hallo" text inside a circle? Currently experiencing issues with the circle display in IE8 and Firefox. Any suggestions on how to fix this would be greatly appreciated. And here is the link to my code snippet: CSS ...

Progressive rendering of a substantial mesh using three.js

How can I efficiently render a large static mesh in three.js, even if it's 2 GB with tens of millions of polygons? My plan is to stream the mesh geometry buffers into indexedDB and render them progressively to the screen, all while maintaining an int ...

Issue with external variable not being updated properly in success callback

Working through an array of data, I make updates to a variable called commentBody during each iteration. However, even though the variable is modified within the loop itself, whenever I try to access it from inside a success callback, it consistently show ...

Is there a way to effortlessly scroll an element when the CSS overflow property is designated as auto?

I need help with creating a testimonial section where two divs automatically scroll inside a fixed-height container. Currently, only one div is scrolling while the other remains static in my code. I have implemented JavaScript for automatic scrolling wit ...

The issue of "Next.js localStorage not being defined persists, despite attempting to

Despite encountering numerous similar questions, I have not been able to find a solution to my specific issue. This is my first experience utilizing Next.js and TypeScript. I am conducting a mock login with REQRES and storing the token in the localStorage ...

Enhancing the readability of modals with Angular Dialog Service

I have been utilizing the Angular Dialog Service to create popup forms on my website. The source code for this service can be accessed here: https://github.com/m-e-conroy/angular-dialog-service/blob/master/README.md However, I am experiencing an issue wit ...

What is the secret behind Node.js's ability to efficiently manage multiple requests using just one thread

After conducting some research on the topic, I noticed that most people tend to focus solely on Non-blocking IO. For instance, if we consider a basic application that simply responds with "Hello World" text to the client, there will still be some executio ...

Obtain decrypted information from the token

I am facing difficulty in retrieving decrypted user data for the current user. Every time a user logs in, they receive a token. After logging in, I can take a photo and send it to the server. Looking at my code, you can see that this request requires a to ...

AngularJS Variable Comparison: A Detailed Analysis

I am currently facing an issue with my custom filter in my code that filters based on gender (male or female). When I click on the male value, female values are also displayed because the female value contains "male" in it. However, when I click on the fem ...