Issues with data binding not being correctly passed to the controller function parameter within the ng-repeat loop

I am in the process of creating a menu that allows users to adjust the CSS on my web application. Within my JavaScript method, I take a string input and then insert it into a URI for a bootswatch CDN. The code functions properly when I manually enter a string, however, when I attempt to use a data-bound variable, things get a bit complicated. In the developer tools, I can see that the HTML displays the data-bound string as it should be. However, when I check the URI that the browser is attempting to retrieve, it is literally adding {{style}} to the URI. I am relatively new to all of this, so please excuse any major errors. I am open to all suggestions and feedback.

Below is the opening HTML tag:

<html data-ng-app="app" lang="en" data-ng-controller="MainCtrl">

Here is the controller:

app.controller('MainCtrl', function($scope) {
    // setting a default for now
    $scope.stylePath = '//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css';
    $scope.styles = ['slate', 'Cyborg', "Darkly", "journal", "Yeti"];
    $scope.setStyle = function(styleName) {
        $scope.stylePath = '//maxcdn.bootstrapcdn.com/bootswatch/3.2.0/' + styleName + '/bootstrap.min.css';
    };
    $scope.changePath = function() {
        $scope.stylePath='//maxcdn.bootstrapcdn.com/bootswatch/3.2.0/slate/bootstrap.min.css';
    };
});

As you can see, I have tried various forms of quotes and both uppercase and lowercase versions in my array. It is important to note that the changePath() function works correctly, whereas setStyle() has never functioned properly when trying to pass it a data-bound value. Providing it with a string literal presents no issues.

Here is the problematic code:

<div class="dropdown">
    <a id="ThemeDropdown" class="btn btn-default" role="button" data-toggle="dropdown" title="Choose a theme">Themes <span class="caret"></span></a>
    <ul class="dropdown-menu" role="menu" aria-labelledby="ThemeDropdown">
        <li role="presentation" data-ng-repeat="style in styles">
            <a role="menuitem" tabindex="-1" href="#/settings" ng-click="setStyle('{{style}}')">{{ style }}</a>
        </li>
        <li role="presentation">
            <a role="menuitem" tabindex="-1" href="#/settings" ng-click="changePath()">hardcode slate</a>
        </li>
        <li>
            <a role="menuitem" tabindex="-1" href="#/settings" ng-click="setStyle('darkly')">hardcode darkly</a>
        </li>
     </ul>
</div>

Additionally, attempting to setStyle() without using quotes around the data binding leads to a parsing error.

Error: [$parse:syntax] http://errors.angularjs.org/1.2.21/$parse/syntax?p0=style&p1=is%20unexpected%2C%20expecting%20%5B%3A%5D&p2=12&p3=setStyle(%7B%7Bstyle%7D%7D)&p4=style%7D%7D)
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:6:450
at cb.throwError (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:168:341)
at cb.consume (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:169:266)
at cb.object (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:177:45)
at cb.primary (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:167:478)
at cb.unary (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:174:160)
at cb.multiplicative (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:173:402)
at cb.additive (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:173:262)
at cb.relational (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js:173:126) <a role="menuitem" tabindex="-1" href="#/settings" ng-click="setStyle({{style}})">
angular.js:10023

Is it feasible to achieve what I am attempting to do? What am I missing here?

Answer №1

<a role="link" tabindex="-1" href="#/preferences" ng-click="updateTheme('{{theme}}')">{{ theme }}</a>

must be changed to

<a role="link" tabindex="-1" href="#/preferences" ng-click="updateTheme(theme)">{{ theme }}</a>

Avoid using any binding inside the function call.

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

Center-aligned footer with a sleek right border in Bootstrap 4.1.1

Presenting my design concept for the footer: https://i.sstatic.net/kxdXJ.png Here is the code snippet for the footer design utilizing Bootstrap 4.1.1: .mainfooter-area { background: #404044; padding: 100px 0; } ... <link href="https://cdnjs.cl ...

zingcharts with multiple lines on x axis representing time

I am facing a rather interesting challenge with plotting data. I want to create a chart where time is the x-axis scale and multiple lines are plotted, each with varying time intervals between data points. While zingcharts has provided documentation on gene ...

Issue with event stopPropagation() or stopImmediatePropagation() not functioning in Bootstrap 5

I'm attempting to implement a span tag with a click event within my according header, however, I don't want to display or collapse my according element. So, I tried using stopPropagation() and stopImmediatePropagation(), but neither worked. H ...

Exploring the implementation of constructors and classes in JavaScript

I have a task to create a class named ShoppingCart with specific instructions: The class should have a constructor that initializes the total attribute to zero and creates an empty dictionary attribute called items. There should be a method named add_ite ...

Achieving default selection of an option value from the server side (PHP) in a select dropdown with AngularJS

The dropdown selection in my code is currently working fine, but now I need to set the default option of the select from the response options obtained from the server side. This matching data is retrieved from the server side using PHP. I am encountering i ...

NextJS not maintaining state for current user in Firebase

I'm working on an app utilizing firebase and nextjs. I've set up a login page, but when I try to retrieve the current user, it returns undefined. This issue began a few days ago while working in react native as well - initially, it was related to ...

Unusual performance issues observed in a flexbox when adjusting window size in mobile Chrome

Encountering an unusual issue with flexbox on a mobile browser. For a visual demonstration, view this gif Specifically happening on Chrome mobile on a Google Pixel phone. Using a resize script to adjust element sizes due to limitations with 100vh: windo ...

What is the best way to prevent event propagation in d3 with TypeScript?

When working with JavaScript, I often use the following code to prevent event propagation when dragging something. var drag = d3.behavior.drag() .origin(function(d) { return d; }) .on('dragstart', function(e) { d3.event.sourceEvent ...

Checking for duplicate entries in an array created with the Angular form builder

I am currently utilizing angular6 reactive form with form builder and form array. The issue I am encountering is duplicate subject entries from the drop down in the form array. How can I implement validation to prevent duplicate entries in the form array? ...

Top spot for locating resolve functions in AngularJS

I'm currently in the process of setting up resolves for my admin panel routes and I'm pondering the best way to store them without cluttering my router with methods. Here's what I have so far: when('/admin', { templateUrl: &ap ...

What could be causing my image not to show up on ReactJS?

I'm new to ReactJS and I am trying to display a simple image on my practice web app, but it's not showing up. I thought my code was correct, but apparently not. Below is the content of my index.html file: <!DOCTYPE html> <html> & ...

Is it necessary to sanitize strings before assigning them as the content of a textarea element?

Consider the situation described below: var evil_string = "..."; $('#mytextarea').val(evil_string); Is it necessary to sanitize an untrusted string before setting it as the value of a textarea element? While I am aware of the importance of han ...

Steps for creating an asynchronous Redis subscriber invocation

My current setup involves a Redis server within AWS ElastiCache. I am publishing messages to a Redis channel and attempting to retrieve these messages through subscription using a JavaScript script as shown below: const redis = require("redis"); const sub ...

A step-by-step guide on setting up a confirmation pop-up message using Gravity Forms

Has anyone attempted to implement a pop-up confirmation message in Gravity Forms? I am also looking to prevent the form from disappearing after submission. By the way, I have selected text as the confirmation type in my Gravity Form settings because I do ...

Minimize the number of clicks needed to navigate using the HTML/JavaScript navigation

On my website, I have a navigation bar that changes the contents of a div when a user clicks on an item. However, if the user clicks multiple times in quick succession, the content changes too many times. I want to ensure that the content only changes once ...

Tips for creating multiple popups using a single line of JavaScript code

I am new to JavaScript and I am attempting to create a popup. However, I am facing an issue in opening two divs with a single line of JavaScript code. Only one div opens while the other remains closed despite trying various solutions found on this website. ...

Creating a Gatsby blog post on Enhancing Your Website with Rich Snippets for Embedded YouTube Videos

I have a website built with Gatsby and the Netlify CMS, and occasionally I want to include embedded YouTube videos in my blog posts. I am looking to implement a videoObject schema for these videos with the following structure: { "@context": "http:// ...

Optimizing Page Load Time in AngularJS with the ng-include Directive

My current challenge involves populating a page in stages. There are multiple categories with varying numbers of items, and my code structure resembles the following (warning: slightly jumbled). $scope.getItems = function(key) { $http.get('get-item ...

"The combination of Node.js, Express, and Angular is causing a continuous loop in the controller when a route is

Currently, I am utilizing node js alongside Express. Angular js files are being loaded through index.html. The code for app.js is as follows: app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); ...

When the forward button is pressed multiple times in the carousel, the alignment changes

I recently noticed that the alignment of my carousel gets disturbed when I repeatedly click the forward button (>). How can I ensure that the carousel moves smoothly one item at a time when I click the forward or backward buttons? <div class="contai ...