Modify the CSS preferences using an object that has been obtained

After the user selects options from a form, I am trying to update my CSS using the settings received from an object. However, I am unsure of how to implement this layout change.

Here is a glimpse of my template:


    div class="btn btn-primary" ng-click="showMenu()">Layout Settings</div>
    <div ng-show="themeSelected">
        <form>
            <div class="row">
                ...
                
            </div>
        </form>

        <button class="btn btn-primary" ng-click="saveChanges(selectedLayout)">Save</button>
        <button class="btn btn-primary" ng-click="cancel()">Cancel</button>
        <div style="color: red" ng-show="errors.length > 0">{{errors}}</div>
    </div>

Upon clicking the Save button, all the defined values are stored in an object. The next step involves using these settings to make real-time changes to the layout.

Below is my controller where the saveChanges function is defined:


'use strict';

(function () {
    angular.module('routerApp').controller('LayoutController', function ($scope, layoutRepository) {
        $scope.showMenu = function() {
            $scope.themeSelected = true;
        };

        $scope.cancel = function() {
            $scope.themeSelected = false;
        };

        $scope.saveChanges = function (selectedLayout) {
            layoutRepository.saveLayoutInfo(selectedLayout);
            $scope.themeSelected = false;
        };
        $scope.selectedLayout = {};

        window.model = $scope.selectedLayout;
    });
}());

This snippet represents the layoutRepository:


'use strict';

(function () {
    angular.module('routerApp').factory('layoutRepository', function ($http) {
        return {
            saveLayoutInfo: function (selectedLayout) {
                console.log(selectedLayout);
                $http({
                    method: "POST",
                    url: "/api/LayoutSettings",
                    data: selectedLayout,
                    cache: false
                });
            }
        };
    });
}());

Answer №1

Utilize this piece of code to extract classnames, keys, and values from your data and attach them to the appropriate element:

    var data = data.split("\n"); //separate the received data by new lines
    for (var i = 0; i < data.length; i++)
    {
        var className = data[i].substr(0, data[i].indexOf("_")); //extract classname before "_"
        var csskey = data[i].substr(data[i].indexOf("_")+1, data[i].indexOf(":");
        var cssvalue = data[i].substr(data[i].indexOf(":")+1).trim().replace("\"",""); remove whitespaces and quotations
       loadCSSIntoControl(className, {key:csskey, value : cssvalue });
    }

function loadCSSIntoControl(classname, css)
{
     if (css.key == "size")
     {
         css.key = "font-size";
     }
     //loop through all elements using Array.prototype.map
     Array.prototype.map.call(document.querySelectorAll("."+classname), function(elem) {
           elem.style[css.key.replace("_", "-")] = css.value; //replace underscore with dash
     });
}

Please note: if the initial part is not a class name, you can easily modify it to another type of selector.

Answer №2

Associate the configurations with a specific scope (are they represented as an object/json? Your output appears unusual)

<button data-ng-style="{
    background: selectedLayout.buttons_color,
    color: selectedLayout.buttons_font_color,
    fontSize: selectedLayout.buttons_size
}">Button</button>

This assumes that the data structure resembles the following:

selectedLayout = {
    buttons_color: "rgb(83, 255, 0)",
    buttons_font_color: "rgb(255, 247, 0)",
    buttons_size: "11px",
    headers_color: "rgb(187, 52, 202)",
    headers_size: "18px",
    info_font_color: "rgb(17, 15, 15)",
    info_size: "12px"
}

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

How Meteor Handles HTTP Requests in its package.js File

When accessing data from an external source at autopublish.meteor.com, our goal is to gather information about a package's latest release tag either from GitHub or the NPM registry: var version; try { var packageJson = JSON.parse(Npm.require(' ...

Is there a way for me to retrieve the specific comment ID that I am looking to respond to?

I have written the code below and I am looking to extract a specific ID to reply to a comment. Can someone please review the snippet below and provide guidance on the necessary steps to achieve this. .anc { cursor: pointer; } <script src="https://c ...

Optimizing Angular for requireJS deletion

We recently developed an Angular directive that utilizes blueimp-fileupload. Everything seems to be working fine until we decided to optimize our code using requireJs. After running the optimizer, we encountered the following error: Error: cannot call m ...

Are jQuery plugins offering accessible public functions?

I am currently working on enhancing the functionality of a jQuery plugin. This plugin serves as a tag system and utilizes autocomplete provided by jQuery UI. Presently, there is no direct method (aside from parsing the generated list items) to determine ...

Exploring various websites simultaneously using window.open

As a newcomer to javascript, I have encountered an issue with the window.open() method that I would like some help with. In my code, I take a user string, modify it in different ways, and then search for these variations. The intention is to open a new wi ...

The Bootstrap 3.3 Carousel is stationary and does not rotate

I am facing a challenge with implementing a Carousel using Bootstrap version 3.3.7 on my website. The code snippet is as follows: <!-- Carousel ================================================== --> <div class="row dark-start d-none d-lg-block"&g ...

Interactive HTML button capable of triggering dual functionalities

I am working on a project where I need to create a button using HTML that can take user input from a status box and display it on another page. I have successfully implemented the functionality to navigate to another page after clicking the button, but I ...

Creating a responsive navigation menu using Bootstrap 4 by merging data from various MySQL tables

I am struggling to create a bootstrap 4 nav-menu using the provided SQL query and code snippets. Below are the tables: TABLE menu -------------------------------------- | id | title | url | | 1 | Home | index.php | | 2 | M ...

Guide to automatically choose the first item and emphasize the chosen selection in AngularJs

I am currently developing an app that showcases a list of items on the left side. By default, the first item is highlighted and its details are displayed on the right side. When a user clicks on any item in the list, that item should be highlighted and its ...

The button in my form, created using React, continuously causes the page to refresh

I tried to create a chat application using node.js and react.js. However, I'm facing an issue where clicking the button on my page refreshes the entire page. As a beginner in web development, please forgive me if this is an obvious problem. You can fi ...

AngularJS - Create Alert Pop-Up for Missing Input Fields

I've been struggling to set up my app so that it displays an alert when the user attempts to submit a form with an empty input box. Despite having a confirmation popup working in another part of the application, I can't seem to figure out why thi ...

The npm command encountered a permission issue when trying to install node-sass

Whenever I run the npm command on my Ubuntu system, I encounter a "permission denied" issue. sudo npm install node-sass EACCES: permission denied, access '/node_modules/node-sass' I have attempted to run the command as a root user or with sudo ...

The parser encountered an unexpected token while attempting to parse the provided string

Struggling to correctly parse a JSON response from a server using node, as it is showing up as a string. Here's an example: "{name:'hello'}" Recreated the issue here: http://jsfiddle.net/x5sup14j/ Tried replace(/'/g, '"'); ...

Determine who the creator of the clicked div is

I'm sorry if my explanation is a bit difficult to comprehend. Here is the code snippet in question: names.push(newName); var strName = newName; var newName = document.createElement('p') newName.setAttribute('id', newName); documen ...

A specific div remains in place as the user scrolls

Imagine a div that is positioned 60px from the top of the screen. What if, as you scroll down, it stops when it reaches 10px from the top and remains there for the rest of your scrolling session? And then, when you scroll back up, it goes back to its ori ...

The width property in Bootstrap is not functioning properly in .NET Core 6

I've exhausted all my options, including documentation and the last 10 stack overflow answers, but nothing seems to be working. I even tried using: <meta name="viewport" content="width=device-width, initial-scale=1"> I attem ...

Achieve the effect of background images fading in once the page loads, then disappearing when an accordion tab is

Currently on a project, I have implemented two background images that cross-fade on this website: www.alexarodulfo.com. I am interested in exploring the following possibilities: 1) Achieving a more subtle fade-in effect for the images, perhaps allowing th ...

Struggling to make React respond to button clicks without resorting to using addEventListener

Can anyone help me figure out why I can't get the onclick handler to execute in reactjs when specifying it inline for a button? The only solution that worked for me was using addEventListener. From what I understand, this code should work: <button ...

Update to react version 18.2.0, router-dom v6, and mui 5 for improved performance

Struggling to convert the following file or code into React's latest version and react-router-dom v6. I attempted it myself but encountered errors related to createBrowserHistory that I couldn't comprehend. My routes are stored in a JSON file and ...

Commitments, the Angular2 framework, and boundary

My Angular2 component is trying to obtain an ID from another service that returns a promise. To ensure that I receive the data before proceeding, I must await the Promise. Here's a snippet of what the component code looks like: export class AddTodoCo ...