What is the best way to apply CSS to a specific row in AngularJS?

I am currently developing a to-do list using AngularJS. It's almost completed but I have a question regarding highlighting the entire row when in editing mode by adding a CSS class "yellow". Unfortunately, I'm unsure how to achieve this.

Additionally, I would like some feedback on whether my coding approach is correct or incorrect.

Here is the JSFiddle link for reference:

http://jsfiddle.net/mcVfK/1338/

Below you can find the code snippets:

HTML:

<div ng-app="myapp">
<div class="container" ng-controller="mainCtrl">
        <h3>Todo List</h3>
        <input type="text" class="form-control" placeholder="create your todos" ng-model="newItem">
        <p class="help-block text-center red" ng-show="!newItem && empty">*Fill the field.</p>
        <br>

        <table class="table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Todo</th>
                    <th>Status</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="todoList in todoLists">
                    <td>{{$index+1}}</td>
                    <td>{{todoList.name}}</td>
                    <td>{{todoList.edit}}</td>
                    <td><a class="btn {{disabled}} pull-right" href="" ng-click="remove(todoList)">delete</a>
                        <a class="btn {{disabled}} pull-right" href="" ng-click="edit($index)">edit</a> </td>
                    </tr>
                </tbody>
            </table>


            <button type="button" class="btn btn-primary btn-lg btn-block" ng-click="add()" ng-hide="editMode">ADD</button>
            <button type="button" class="btn btn-default btn-lg btn-block" ng-click="update(newItem)" ng-show="editMode">UPDATE</button>
        </div>
</div>

JavaScript file:

var app = angular.module("myapp", []);
app.controller("mainCtrl", ["$scope", "$rootScope", function($scope, $rootScope){
    $scope.empty = false;
    $scope.editMode = false;

    $scope.todoLists = [{name : "one", edit : "false"},{name : "two", edit : "false"}];

    $scope.add = function(){
        if(!$scope.newItem == ""){
            $scope.todoLists.push({name:$scope.newItem, edit:"false"});
            $scope.newItem = "";
            $scope.empty = false;
        }else{
            $scope.empty = true;
        };
    };

    $scope.remove = function(item){
        var index = $scope.todoLists.indexOf(item);
        $scope.todoLists.splice(index, 1);
    };

    $scope.edit = function(index){
        $rootScope.ind = index;
        $scope.newItem = $scope.todoLists[$rootScope.ind].name;
        $scope.editMode = true;
        $scope.disabled = "disabled";
        $scope.todoLists[index].edit = "true";
    };

    $scope.update = function(item){
        if(!$scope.newItem == ""){  
            $scope.todoLists[$rootScope.ind].name = item;
            $scope.todoLists[$rootScope.ind].edit = "false";
            $scope.editMode = false;
            $scope.newItem = "";
            $scope.disabled = "";
        }else{
            $scope.empty = true;
        };
    };


}]);

CSS file:

.yellow{
        background:yellow;
    }
    .red{
        color:red;
    }

Answer №1

If you want to style elements dynamically in AngularJS, consider using the ng-class directive. https://docs.angularjs.org/api/ng/directive/ngClass

Modify

<tr ng-repeat="todoList in todoLists">

to

<tr ng-repeat="todoList in todoLists" ng-class="{yellow: editMode && $index == ind}">

Answer №2

Here's a quick example inspired by your fiddle. The concept revolves around using ng-class to trigger a function that assigns a class based on a condition. For instance, when you select a todo for editing, you can set it as the selectedTodo on $scope:

  $scope.edit = function(index){
      $scope.selectedToDo = $scope.todoLists[index];
      ....
  };

You can then apply an ng-class to your <tr> element to determine if the todo is selected and apply a specific class, such as .highlighted, if it is.

  $scope.isSelected = function(item) {
      if ($scope.selectedToDo === item) {
          return 'highlighted';
      }
  };

Answer №3

Here is a basic example demonstrating how to utilize the ng-class directive with an existing red class in the demonstration:

<tr ng-repeat="item in items" 
    ng-class="{red:active.item == item}" 
    ng-click="active.item=item">

This is how you would set it up in the controller:

$scope.active={item:null}

Answer №4

Here's an alternative method for assigning different classes to different rows:

ng-class-odd="'odd'" ng-class-even="'even'"

Check out the code snippet below:

<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  <li ng-repeat="name in names">
   <span ng-class-odd="'odd'" ng-class-even="'even'">
     {{name}} &nbsp; &nbsp; &nbsp;
   </span>
  </li>
</ol>

Don't forget to add the following CSS styling:

.odd {
  color: red;
}
.even {
  color: blue;
}

Note that this directive can only be used within the scope of an ngRepeat.

We hope this information proves useful to you!

Answer №5

There are numerous approaches to execute this concept. A simple fix could involve passing the $event parameter through the edit function of the specific row.

<a class="btn {{disabled}} pull-right" href="" ng-click="edit($index,$event)">edit</a> </td>

You can then utilize $event.target to reach the clicked element. By using

angular.element($event.target).parent().parent()
, you can access the row element.

Function for Editing

    var EditRow;
    $scope.edit = function(index,$event){
        EditRow = angular.element($event.target).parent().parent(); 
        EditRow.css( "background-color", "#ccc"); // modify css style
            $rootScope.ind = index;
            $scope.newItem = $scope.todoLists[$rootScope.ind].name;
            $scope.editMode = true;
            $scope.disabled = "disabled";
            $scope.todoLists[index].edit = "true";
        };

Function for Updating

$scope.update = function(item){
    if(!$scope.newItem == ""){  
            $scope.todoLists[$rootScope.ind].name = item;
            $scope.todoLists[$rootScope.ind].edit = "false";
            $scope.editMode = false;
            $scope.newItem = "";
            $scope.disabled = "";
        }else{
            $scope.empty = true;
        };
    EditRow.css( "background-color", "#fff"); // Reverting back to original style
    };

To see a live demonstration, visit this link.

Answer №6

Check out the updated jsfiddle here: http://jsfiddle.net/mv0ne441/ To achieve row highlighting in the table using the 'ng-class' directive, you can apply it to the 'tr' element as mentioned in your question.

<tr ng-repeat="todoList in todoLists" ng-class="{true:'yellow', false:'red'} [todoList.edit == 'true']">
    <td>{{$index+1}}</td>
    <td>{{todoList.name}}</td>
    <td>{{todoList.edit}}</td>
    <td><a class="btn {{disabled}} pull-right" href="" ng-click="remove(todoList)">delete</a>
                    <a class="btn {{disabled}} pull-right" href="" ng-click="edit($index)">edit</a>
    </td>
</tr>

Answer №7

If you want to dynamically add a CSS class based on the selected index in AngularJS, you can make use of the ng-class directive.

Sample HTML snippet:

<tr ng-repeat="todoList in todoLists" ng-class="{'yellow': selectedIndex == $index}">

Angular JS function examples:

 $scope.edit = function(index) {
   $scope.selectedIndex = index;
   ...
 };

 // Reset the selectedIndex to -1
  $scope.update = function(item) {
  if (!$scope.newItem == "") {
     $scope.selectedIndex = -1;
     ...
  };

Check out the Live Demo on JSFiddle

Answer №8

i have implemented the latest code updates, please review it.

Make sure to utilize ng-class for styling.

var app = angular.module("myapp", []);
app.controller("mainCtrl", ["$scope", "$rootScope",
  function($scope, $rootScope) {
    $scope.empty = false;
    $scope.editMode = false;

    $scope.todoLists = [{
      name: "one",
      edit: "false",
      "todoeditclick": false
    }, {
      name: "two",
      edit: "false",
      "todoeditclick": false
    }];

    $scope.add = function() {
      if (!$scope.newItem == "") {
        $scope.todoLists.push({
          name: $scope.newItem,
          edit: "false"
        });
        $scope.newItem = "";
        $scope.empty = false;
      } else {
        $scope.empty = true;
      };
    };

    $scope.remove = function(item) {
      var index = $scope.todoLists.indexOf(item);
      $scope.todoLists.splice(index, 1);
    };

    $scope.edit = function(index) {
      $rootScope.ind = index;
      $scope.newItem = $scope.todoLists[$rootScope.ind].name;
      $scope.editMode = true;
      $scope.disabled = "disabled";
      $scope.todoLists[index].edit = "true";
    };

    $scope.update = function(item) {
      if (!$scope.newItem == "") {
        $scope.todoLists[$rootScope.ind].name = item;
        $scope.todoLists[$rootScope.ind].edit = "false";
        $scope.todoLists[$rootScope.ind].todoeditclick = false;
        $scope.editMode = false;
        $scope.newItem = "";
        $scope.disabled = "";

      } else {
        $scope.empty = true;
      };
    };


  }
]);
.yellow {
  background: yellow;
}
.red {
  color: red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="myapp">
  <div class="container" ng-controller="mainCtrl">
    <h3>Todo List</h3>
    <input type="text" class="form-control" placeholder="create your todos" ng-model="newItem">
    <p class="help-block text-center red" ng-show="!newItem && empty">*Fill the field.</p>
    <br>



    <table class="table">
      <thead>
        <tr>
          <th>#</th>
          <th>Todo</th>
          <th>Status</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="todoList in todoLists" ng-class="{yellow:todoList.todoeditclick}">
          <td>{{$index+1}}</td>
          <td>{{todoList.name}}</td>
          <td>{{todoList.edit}}</td>
          <td><a class="btn {{disabled}} pull-right" href="" ng-click="remove(todoList)">delete</a>
            <a class="btn {{disabled}} pull-right" href="" ng-click="edit($index);todoList.todoeditclick=!todoeditclick">edit</a> 
          </td>
        </tr>
      </tbody>
    </table>



    <button type="button" class="btn btn-primary btn-lg btn-block" ng-click="add()" ng-hide="editMode">ADD</button>
    <button type="button" class="btn btn-default btn-lg btn-block" ng-click="update(newItem)" ng-show="editMode">UPDATE</button>
  </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's the best way to search through various addresses for the source in an image tag?

In my current Laravel 5.8 project, I am faced with the task of searching through three different image sources for an img tag. First, I attempt to load the image from "". If that fails, I try a second URL like "". Should both attempts be unsuccessful, I th ...

the three.js code runs smoothly on JSfiddle, but it does not seem to be working properly

Check out this basic three.js code snippet for generating custom geometry http://jsfiddle.net/67Lgzjpb/. After attempting to run this code directly in my browser (not via JSFiddle), an error message pops up: TypeError: geom.computeCentroids is not a funct ...

"Optimizing Image Display in Web Browsers

Currently, I am using JavaScript to dynamically size a transparent .gif on my website. The original image size is approximately 200x200 pixels, but it's usually resized to be between 600x600 and 800x800. When viewing the resized image in IE8 and FF3, ...

Navigating through pages can result in Ruby Locales becoming misplaced

I am encountering an issue with my website where different pages are meant to be shown for different URLs (locales). The problem arises when I navigate from one page to the next, as it defaults back to the default URL instead of staying on the specific sit ...

What is the best way to find a match for {0} while still allowing for proper

I am working on developing a text templating system that allows for defining placeholders using {0}, similar to the functionality of .Net's string.format method. Here is an example of what I am aiming for: format("{0}", 42), // output ...

Having difficulty establishing a connection between my node.js application and the database

I've been struggling to establish a connection between my application and the database. Despite attempting the code below, my models are still not being recognized. const MongoClient = require('mongodb').MongoClient; const assert = require(& ...

What is the best way to display data from an Excel spreadsheet on my website?

I'm faced with a challenge in my Excel spreadsheet- I have a mix of numbers and text that I want to turn into graphical representations on a webpage. I'm considering using Python or PHP to achieve this as HTML alone doesn't seem up to the ta ...

Automatically assigning a FormData key/value pair upon clicking using Puppeteer in NodeJS

While working on a NodeJS project, I am using Puppeteer to fill out a form. So far, the regular type and click functions work perfectly. After clicking the "submit" button, a POST request is sent to the server with some form data. I want to add a key/value ...

Bring in a particular module from the natural library (webpack)

I have been utilizing the npm natural library for tokenization, specifically in one line of code: let token = natural.StemmerJa.prototype.tokenizeAndStem(searchWord, true); My concern lies in how to properly import it in webpack, given that tokenizeAndSte ...

Do server-side or client-side rendering render dynamic routes in Next.js?

I'm currently working on a project that necessitates server-side rendering for SEO benefits. I am utilizing Next.js and React, implementing Next.js dynamic routing for this purpose. To test if the setup is functioning correctly, I developed a basic p ...

React Native package identifies a primary module for handling HTTPS requests

For my latest project, I decided to experiment with incorporating HTTPS. I began by creating a new project using expo init test and then installed the HTTPS library with npm install https. Next, I made edits to App.js by adding the following line at the t ...

Executing commands upon receiving socket messages (socket.io/node.js)

Whenever a new instance of GameServer is initialized, the socket and listeners are configured in the following manner: var GameServer = function() { this.player = new Player(); var that = this; // Setup sockets and listeners var socket = ...

What is the mechanism behind the functioning of "3D Meninas" (CSS/Animation)?

Recently stumbled upon a fascinating website called "3D Meninas", showcasing an impressive 3D animation effect. Upon examining the HTML code, I noticed there was no mention of any <script> tags or events, leading me to believe that it operates solely ...

MaterialUI is not displaying input styling correctly

I'm a beginner with MaterialUI and I seem to be missing something simple. This is the code I am trying to work with: <Container> <FormControl> <FormGroup> <InputLabel htmlFor="email">Email addre ...

"RecognitionAudio variable missing" and "InactiveRpcError occurred" [Utilizing the Google text-to-speech API]

I have a goal I'd like to achieve. A user communicates with a web browser. The web browser records the user's voice as a WAV file using Recorder.js and sends it to a server running on Google App Engine Standard environment with Python 3.7. The ...

What is the solution to fixing the error message "SyntaxError: missing ) after argument list" in JavaScript?

I wrote some code in HTML/JavaScript/PHP, and in the 3rd echo statement, I added a button that calls the deleteAttribute() function when clicked. However, I encountered an error at the 3rd echo statement with (type = "button"): "Uncaug ...

Find the mean of three numbers stored in an array of objects

I am currently working on a school assignment that requires me to develop a function for calculating the average mark of 3 students using an existing object in an array. Below, you can see the array and function that I have been working on as part of this ...

Establish Angular data for all fields in the form

Being a beginner in Angular, I'm struggling with creating a form to update user information. Here's a snippet of my controller: // Fetch organization data from the database dataService.allOrganization().then(function ...

Javascript failing to choose background color from an array

I am attempting to create a subheader with varying colors, similar to the one found on the Ask Different page. However, instead of manually assigning colors, I am looking to have it randomly select a color from a Javascript array. I have already outlined ...

What methods are available to verify all my (JavaScript) AJAX calls when they are being sent to Node.js?

My web app sends hundreds of HTTP requests to a Node.js API I created. I need to ensure that only authenticated requests are accepted by Node.js. The issue at hand: I don't want to manually update each AJAX request in my JavaScript code to include a ...