Is it possible to connect ng-model with a style tag?

Is it feasible to create a basic template editor using angularjs where an input field with an ng-model can be connected to a style tag to control the css on an entire page rather than applying it to a specific element with inline styling? Could something like this be achieved?

<!doctype html>
<html lang="en" ng-app>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="js/angular.min.js"></script>
    <style>
        html, body { height:100%; margin:0; padding:0; }    
            div, ul, li, ol, span { margin:0; padding:0; }

    </style>
</head>
<body>
    <textarea type="text" ng-model="data.style" placeholder="enter style"></textarea>
</body>
</html>
<script>

    window.addEventListener('load', function(){

        var style = document.createElement('style');
        var textnode = document.createTextNode('{{data.style}}');
        style.appendChild(textnode);

        document.querySelector('head').appendChild(style);


    }, false)

</script>

Answer №1

If you need to dynamically load an entire style sheet, here's how you can do it:

HTML

<!DOCTYPE html>
<html ng-app="myApp" ng-controller="myCtrl">

  <head>
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="33525d54465f52411d594073021d011d07">[email protected]</a>" data-semver="1.2.4" src="http://code.angularjs.org/1.2.4/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" ng-href="{{styleHref()}}" />
    <script src="script.js"></script>
  </head>

  <body >
    <div class="box"></div>
    <textarea ng-model="data.style"></textarea>
  </body>
</html>

JS

angular.module('myApp', [
    ]).
    controller('myCtrl',function($scope) {
      $scope.data = { style: "style-1" }; // can come from init func, http call, etc
      $scope.styleHref = function() { return $scope.data.style + ".css"; };
    });

You can check out this Plunkr for a practical example

Answer №2

Achieving this is possible, but it's important to understand the constraints involved. A code snippet like the one below is acceptable:

  <head>
    <style ng-bind="myStyle"></style>
  </head>

  <body>
    <h1>Type Style Here</h1>
    <textarea ng-model="myStyle"></textarea>
  </body>

However, a code structure like the following should be avoided:

<head>
  <style>
   h1 { 
      background-color: {{color}}
   } 
  </style>
</head>

<body>
  <h1>Type Background Color Here</h1>
  <input ng-model="color" /> 
</body>

If you wish to interpolate styles as shown in the second example, you must handle the interpolation elsewhere (e.g., in your controller) and then bind the final interpolated strings. The reason "{{color}}" won't function correctly is because it will attempt to insert illegal HTML nodes inside the style since it assumes it is working within HTML and not CSS.

For a functional demonstration, refer to the link provided below:

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

How to transform a Dictionary containing lists of objects into JSON using C#

In my database, I have two tables with a one-to-many relationship. States have many cities. I retrieve this data from the database and convert their relationships into objects using C# logic. I need to convert Dictionary<State, List<City>> to ...

How can we prevent the HTML escaping of text children in React.createElement?

Let's examine the call to React.createElement: React.createElement('span', null, null, ['&gt;&lt;',]) When executing this code, React will escape the characters &gt; and &lt;. Is there a method to prevent these sp ...

Vue encounters an issue when trying to access a specific field within an array of objects

Consider the following data structure: rules:[ 0:{ subrule1:'', subrule2:'', subrule3:'' }, 1:{ subrule1:'', subrule2:'', subrule3:'' } ...

Angular.js: Utilizing ng-repeat to iterate through items within an object

There are two ng-repeats on the page that share an Object. The items should only be repeated if they match the type data. Sample Object $scope.events = [ { date: "1/16/13", time: "11:30", ...

The design of Foundation's 4 form dropdown is not displaying correctly on Internet Explorer versions 8 and below

During the development of a website using Foundation 4 framework, I encountered an issue with form dropdowns not displaying correctly on Internet Explorer 8 and older versions. Instead of using Foundation's javascript rendering, they appear as the def ...

Connect two radio buttons across separate forms

I am encountering an issue with two radio buttons that I am trying to link together. The problem arises because they are located in two separate form elements, causing them not to function as intended. It is important for the forms to be utilized in Bootst ...

Bottom-aligned footer that remains in place instead of sticking to the page

I am attempting to position a footer at the bottom of the page, without it being sticky. Instead, I want it to remain at the bottom in case the user scrolls down there. Although it technically "works," there appears to be some white space below the footer ...

"Exploring the relationship between Typescript and Angular: transforming variables within different

Ever since I made the switch from JavaScript to TypeScript (Version 2.1.5), I have been facing an issue with the code that filters date selection. Despite my efforts, I haven't been able to find a good fix for it yet. Here are the two date-pickers: F ...

Expanding the size of a div using the Bootstrap grid system

I need to customize the width of the date column on my inbox page so that it displays inline without breaking the word. Even when I use white-space: nowrap, the overflow hides it due to the fixed width. I want the name and date classes to be displayed in ...

Ways to display and conceal menu depending on initial view and scrolling

On my website, I have implemented two menus - one to be displayed when the page loads and another to show up when a scroll occurs. You can view my page here. The goal is to have the white part visible when the position is at the top, and switch to the blu ...

Solving the Issue of Handling Custom Events in Javascript

I've been experimenting with a simple CodePen that features a basic table with three rows. I'm trying to attach event handlers to each row in the table and trigger the event by pressing a button. However, I'm facing an issue where the attac ...

What are the steps for implementing this javascript code in an HTML document?

Recently, I've been seeking advice on how to address the issue of wanting a button click to automatically select the search box on my website. Suggestions have pointed towards using Javascript for this functionality, with the following code recommend ...

How Jquery Can Be Used to Dynamically Add Extra Rows in HTML Without Submitting Data via POST Requests

When using jQuery to dynamically add extra rows to an HTML table, I encountered an issue where the fields of the extra rows were missing in the $_POST array when submitting the form. Can you please review the code and provide a solution to fix this problem ...

Can one verify if an Angular application currently has active app modules running?

I am developing a unique plugin for Angular that is designed to automatically initialize an Angular app module if none are found. However, if there is already a running or declared ng-app, my plugin will utilize that existing module instead. Here is an i ...

Customize the React Material UI Autocomplete with a unique dropdown menu and a convenient Add Button feature located at

Seeking assistance in creating an autocomplete feature in React using Material-ui, with a unique custom dropdown design including a button labeled Add New Element positioned at the bottom. https://i.sstatic.net/6rY99.png Various attempts have been made t ...

Preserve page configurations upon page refresh

I'm currently in the process of creating a 'user settings' form. Each list item represents a different section, such as Updating username, Updating email, and Changing password. It looks something like this: <li> <header>Ti ...

The usage of event.returnValue has been phased out. It is recommended to utilize the standard event.preventDefault()

Here's the code snippet I'm working with: <script> $(document).ready(function () { $("#changeResumeStatus").click(function () { $.get("{% url 'main:changeResumeStatus' %}", function (data) { if (data[&apos ...

Tips for concealing the body description on the homepage of a blogger website

I want to conceal this description This is my blog and I am facing an issue where I need to hide the description on the home page. I have tried using color:white which worked initially, but when I moved the description to the top or left, the black backgro ...

What is the best way to implement a link instead of a string within a custom JavaScript function?

I am looking for a way to replace parameters in a string with the values provided using a helper function - type FormatStringParameter = string | number; /** * Helper function to substitute parameters in a string with the specified values * * @param in ...

What steps should be followed in order to integrate two themes within a single DOM element while utilizing a ThemeProvider?

<ThemeProvider theme={theme}> My goal is to utilize two themes simultaneously on a single DOM element using a theme provider. style={theme.flexRowLeft} Struggling with incorporating multiple themes at once, I am currently restricted to applying on ...