Modify input field background color

In my Angular project, I have an input field structured like this:

<input class="form-control" type="text" ng-model="newBook.color">

Whenever the value in this input changes, I want to dynamically change the background color of a specific div.

Within my controller, I have defined the following variables:

$scope.newBook = {};
$scope.newBook.color = "";

$scope.color = ->
  return "background-color: " + $scope.newBook.color;

The div that should reflect the color change looks like this:

<div ng-style="{{color()}}"></div>

Despite my efforts, I encountered an error message stating:

Error: [$parse:syntax] Syntax Error: Token ':' is an unexpected token at column 17 of the expression [background-color:]

Answer №1

Here's a sample I put together: https://jsfiddle.net/chelogui/2h3hrj1x/

Code Snippet:

<div ng-app="appTest">
    <div ng-controller="contr as controller">
        <input class="form-control" type="text" ng-model="controller.color" />
        <div id="divTest" style="background-color: {{ controller.color }}"></div> 
    </div> 
</div>

Javascript Section:

angular.module('appTest', [])
    .controller('contr', [function () {
    var self = this;
    self.color = "red";
}]);

Css Example:

#divTest {
    width: 100px;
    height: 100px;
    border: 1px solid black;
    margin-top: 10px;
}

Answer №2

Take a look at this demonstration:

To achieve the desired outcome, you must modify your color function like so:

angular.module('myApp',[])
   .controller('myFirst',['$scope',function($scope){
      $scope.newBook = {};
      $scope.newBook.color = "red";
      $scope.color = function(){
        return "{'background-color' : '"+$scope.newBook.color+"'}";
      }
}])

Verify with the following code snippet:

angular.module('myApp',[])
.controller('myFirst',['$scope',function($scope){
    $scope.newBook = {};
    $scope.newBook.color = "red";
    $scope.color = function(){
        return "{'background-color' : '"+$scope.newBook.color+"'}";
    }
}])
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <div ng-app="myApp">
    <div  ng-controller="myFirst" ng-style="{{color()}}">Ajay</div></div>

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

What is the process for executing a GET/POST request and receiving a JSON response on a webpage?

I am working on a page that has a JSON result, with both get and post methods in the controller. There are two submit buttons - one that redirects to the Post method and another that goes to the JsonResult method (named AddTableData). How can I set this up ...

How can I eliminate the outline from the modal backdrop using Material UI styling shown in the image provided?

https://i.stack.imgur.com/cBCzd.png After attempting to remove the border and box shadow, I am still encountering issues with lines appearing only when clicking on the modal body. The modal styling code has been omitted as it primarily includes flex styli ...

Broadcast and listen to events in AngularJS using `$rootScope.$emit`

I am currently working on a large Angular app and I have encountered the need to trigger an event using $rootscope.$emit, and then listen to this event inside a factory. Doing this inside a controller is not feasible because the controller hasn't load ...

Implementing React hooks to efficiently remove multiple items from an array and update the state

Looking for help on deleting multiple items from an array and updating the state. I have selected multiple items using checkboxes, which are [5, 4, 3]. My goal is to remove all these items from the array based on their ids and then update the state accordi ...

Choose a column in a table and organize it in ascending or descending order with the help

Does anyone know how to use JavaScript (without frameworks or plugins) to select and sort a specific column in a table? <table> <thead> <tr> <td>Col1</td> <td>Col2&l ...

Could you please suggest a method to position a button that is not entirely on the right side?

As I work on building my website, I am faced with the challenge of aligning a button directly under an image. I have utilized HTML tags and assigned a class to it for CSS styling purposes. However, when it comes to setting the alignment using the 'tex ...

I'm trying to understand a JSON object that has multiple key names pointing to a single value. How can I properly interpret this in

Encountering an object with a strange key. const obj = { formValues: { 'TOTAL;_null_;_null_;3;_null_': "100" 'billing;_null_;_null_;1;_null_': "Y" 'billing;_null_;_null_;2;_null_': "Y" 'billi ...

Shuffle order of AngularJS ng-repeat array

I am struggling to create a basic grammar quiz where I need to randomly sort an array using ng-repeat. The goal is to display both correct and incorrect sentences in random order. Below you can find my code snippet: (function(angular) { 'use str ...

Chinese Input Causing Triggered Computed Problem in Vue 2

Currently working with vue2 on my development project. I have noticed that the computed property only activates when Chinese input is typed, either through keyup or keydown. (example: ㄨㄛˇ => 我 It only triggers once instead of three times when f ...

Is it acceptable to reference all JS files in index.html in Angular?

Just dove into my first AngularJS project! Following a tutorial where they put everything in one controller, but now I want to separate controllers and services. I managed to split them into different JS files, but is it best practice to list all these f ...

Can you explain the functionality of this CSS rule: ~"-moz-calc(..)"?

As I was reviewing some CSS code, I came across a rule that appeared like this: width: ~"-moz-calc(100% - 10px)"; While I am familiar with -moz-calc, I am puzzled by why this is enclosed in a string and what exactly is the purpose of the '~' sy ...

Relocate the resizable handles in jQuery outside of the div elements

I currently have 3 nested divs. Using jQuery $(function() { $("#div1").resizable({ handles: "n, e, s, w, nw, ne, sw,se" }); $("#div1").draggable(); }); Within the HTML structure <div id="div1" style="left: ...

Preventing Div items from rearranging during size transitions using toggleClass

When I click on an element with the ID "id", I use toggleClass to resize a div from 10px to 500px in width. This is done partly to show/hide content. However, the issue arises when the transition occurs and the contents of the div start rearranging, overfl ...

Struggling to dynamically generate class names with clsx in combination with TailwindCss

Greetings! I am a JavaScript developer who is not very skilled yet, working with React and Next. Specifically, I am using this template When it comes to declaring component class names, I have been using a utility function that combines tailwind-merge and ...

CSS: Specify `left:0` or `left:0px` to position

Is there a difference between using left:0; and left:0px;? From what I've noticed, both seem to work fine without any issues in Firefox's error console. Just curious if they have the same interpretation. I am working on some JavaScript that invo ...

Adjust the margin-top based on the height of another element

I'm facing an issue with two fixed navbars positioned one under the other. I used the 'fixed-top' class to fix both at the top, but the margin-top I added to make them align is not responsive. Is there a way to make the margin-top responsiv ...

Analysis of printing functionality across Chrome, Safari, and Firefox browsers

When utilizing the print function of various browsers to save web content in a PDF file, I have observed that each browser behaves differently. This becomes an issue when the content spans multiple pages. For instance, Chrome prints correctly while Safari ...

I'm having trouble adding two Owl carousels in two separate rows

I am trying to incorporate two owl-carousel sliders on a single HTML page. For example, I want owl-carousel1 in row 1 and owl-carosoul2 in row 2. <div class="item"> <!-- Item Image --> <div cl ...

Are you ensuring compliance with licensing in your Webpack bundles?

Can webpack be used to verify license compliance? I'm looking for a way to ensure that the license headers from all modules built by webpack are included in the final output file. How can we confirm this is happening? Furthermore, I am also intereste ...

Calculating the total length of an SVG element using React

Looking to animate an SVG path using React (similar to how it's done in traditional JavaScript: https://css-tricks.com/svg-line-animation-works/), but struggling when the path is created using JSX. How can I find the total length of the path in this s ...