Exploring the use of Angular with tables: applying classes dynamically using ngClass and repeating items using

My table is generated from a Web Service JSON, each row has a button to mark it for deletion. When you click the button, a JS alert displays the ID of the row element, and I also need to add the 'danger' bootstrap class to the row. Now, I can capture the row element ID when clicking the button and store it in a list to be sent to the web service later.

This is how my view looks:

<table class="table table-condensed">
    <tr>   
        <th>#</th>
        <th><a href="" ng-click="sortField = 'ordre'; reverse = !reverse">Prioritat</a></th>
        <th><a href="" ng-click="sortField = 'nomAtribut'; reverse = !reverse">Atribut</a></th>
        <th><a href="" ng-click="sortField = 'nomAtribut'; reverse = !reverse">Tipus</a></th>
        <th><a href="" ng-click="sortField = 'midaAtribut'; reverse = !reverse">Mida</a></th>
        <th><a href="" ng-click="sortField = 'atributObligatori'; reverse = !reverse">Obligatori</a></th>
        <th><a href="" ng-click="sortField = 'observacions'; reverse = !reverse">Observacions</a></th>
    </tr>
    <tr ng-repeat="(key, value) in atrb">
        <td>
            <a href="" ng-click="alert(value.idatributs_actiu)" ng-model="elimina"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></a>
        </td>
        <td>
            <input type="number" ng-model="value.ordre" value="value.ordre"   />
        </td>
        <td>
            <input type="value.valor" ng-model="value.nomAtribut" value="value.nomAtribut"   />
        </td>
        <td>
            {{value.valor}}
        </td>
        <td>
            <input type="value.valor" ng-model="value.midaAtribut" value="value.midaAtribut"   />
        </td>
        <td>
            <input type="checkbox" ng-model="value.atributObligatori" value="value.atributObligatori" ng-true-value="'Si'" ng-false-value="'No'" />
        </td>
        <td>
            <input type="value.valor" ng-model="value.observacions" value="value.observacions"   />
        </td>
    </tr>

Here's the controller:

$scope.alert = function (index) {
    $window.alert('click a borrar id: ' + index); 
    $scope.addAtributsExistentsEliminar(index);
    $scope.elimina = true; 
    $scope.class = 'danger';
}

I've attempted to implement this using ngClass with reference to other examples, but I'm not seeing any output, not even the JavaScript alerts or console messages.

Edit:

Below is the complete controller code:

// Edits asset types
assets.controller('EditaTipusCtrl', function ($scope, $http, $routeParams, $window) {

        $scope.refresh = function () {
            $http.get('http://10.0.203.73/WS/ws.php/tipusactius/getDetails/' + $routeParams.id).success(function (data) {
                $scope.atrb = data;
            });
        };

        $scope.alert = function (index, rowScope) {
         //   rowScope.class = 'danger';
            $window.alert('click a borrar id: ' + index); 
            $scope.addAtributsExistentsEliminar(index); 
            $scope.elimina = true; 
            rowScope.addClass = 'danger';
        }

        $scope.refresh();

        $http.get('http://10.0.203.73/WS/ws.php/getCombo/1').success(function (data) {
            $scope.options = data;
        });

        $scope.nousAtributs = [];
        $scope.atributsExistentsEliminar = [];

        $scope.addNewLine = function () {
            var newRow = {
                "nomAtribut": "",
                "tipus": "",
                "mida": '',
                "prioritat": "",
                "obligatori": "",
                "observacions": "",
                "nomTipusActiu": $routeParams.id 
            };
            $scope.nousAtributs.push(newRow);
        }

        $scope.addAtributsExistentsEliminar = function (id) {
            $scope.atributsExistentsEliminar.push(id);
        }

        $scope.showAtributsEliminar = function(){
            angular.forEach($scope.atributsExistentsEliminar, $scope.show);
        }

        $scope.show = function (id) {
            $http.get('http://10.0.203.73/WS/ws.php/tipusactius/edita/elimina/' + id + '.json').success(function (data) {
                $scope.sts = data.status;
                $window.alert($scope.sts);
            });

            if ($scope.sts.status == 'IN_USE') {
                $window.alert('Aquest atribut no es pot eliminar perque és en ús');
            }

        }

        $scope.saveChanges=function(){
            angular.forEach($scope.atrb, $scope.sendChanges);
            angular.forEach($scope.nousAtributs, $scope.saveNewAttributtes);
            $('#myModal').modal('show');
            $scope.refresh();
        }

        $scope.sendChanges=function(atribut){
            $http.post('http://10.0.203.73/WS/ws.php/tipusactius/edita', atribut).success(function (data) {
                $scope.atrb = data;
            });
        }

        $scope.saveNewAttributtes=function(atribut){
            $http.post('http://10.0.203.73/WS/ws.php/tipusactius/edita/nouatribut', atribut).success(function (data){
                $scope.atrb = data;
            });
        }

        $scope.removables = function () {

        }

    });

Solved:

Your current code tries to use the parent scope, which is why it's not working as you expected. You can simply pass in the scope to the alert function like so

$scope.alert = function (index, rowScope) {
  ...
  rowScope.class = 'danger';
}

with your template looking like

...
   <tr ng-repeat="(key, value) in atrb" ng-class="class">
      <td>    
         <a href="" ng-click="alert(value.idatributs_actiu, this)"...

Fiddle - https://jsfiddle.net/y0rtLhyj/

Answer №1

Your existing code is attempting to utilize the parent scope, which is causing it to not function as desired. To resolve this issue, you can simply include the scope as an argument in the alert function. Therefore,

$scope.alert = function (index, rowScope) {
  ...
  rowScope.class = 'danger';
}

and update your template like so

...
   <tr ng-repeat="(key, value) in atrb" ng-class="class">
      <td>    
         <a href="" ng-click="alert(value.idatributs_actiu, this)"...

Fiddle - https://jsfiddle.net/y0rtLhyj/


However, a more appropriate approach would involve incorporating an indicator in your value object to signify that it has been deleted. This indicator can then be used to determine the application of classes through ng-class. By following this method, you avoid storing view-related attributes (such as class) in your controller.

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

Unusual Characteristics of Synchronous Ajax Requests in JavaScript

First and foremost, I'd like to apologize if my approach seems unconventional. My background is primarily in C development, so I tend to tackle AJAX issues in a way that reflects my experience in C programming. The scenario at hand involves a script ...

The Window.print() function may experience compatibility issues across different browsers

When attempting to utilize the Window.print() function, I encountered an issue where it works perfectly in Google Chrome but not in Mozilla Firefox. Attached are screenshots displaying the problem at hand. What could be causing this discrepancy? Furthermor ...

The new Facebook login button in my app seems to be glitchy as it fails to redirect users to the appropriate page after

I am working on a web application and have successfully integrated Facebook login from developers.facebook.com. However, I am facing an issue where after the user logs in with their Facebook credentials, they are not redirected to my application. Additiona ...

Utilize a JavaScript function on an element that is generated dynamically

I am encountering an issue with my autocomplete function. It works perfectly fine for the input field with the id "field10" that is already created. However, when I dynamically generate new input fields, the function does not seem to work on them. I have ...

Guide on modifying cube material dynamically in WebGL at runtime

Currently, I am utilizing three.js to create animations. My goal is to dynamically modify the material of a cube mesh. Below is an example: // Create cube geometry var material1 = [new THREE.MeshBasicMaterial({color:0xBEE2FF}),.....]; var geometry = new ...

Unique Soundcloud visualization using webglonDeletegist

After going through the SoundCloud documentation, I have been trying to figure out how to create a visualizer for SoundCloud tracks. The challenge is that in order to achieve this effectively, I need access to the source waveform. I suspect that direct acc ...

Implement the maskmoney library in your input fields

In the form below, I am automatically adding inputs using a JavaScript function like this: $('.Preco1').maskMoney({ decimal: '.', thousands: ' ', precision: 2 }); $('.Preco1').focus(); $('#sub').maskMon ...

What could be causing the issue of my Angular service value not reflecting changes in my scope?

Take a look at this simple JSFiddle I created to showcase what I believed would be a dynamic service value that could be monitored by any controller it was injected into. Here's the Angular code: var app = angular.module("application", []); app.serv ...

What is the best way to control the class name of elements using jQuery in an MVC4 application?

Among the <li> elements, one of them contains the class "current". Determining which <li> is the current one. View below: @{ int k = 10; //the value changes with each request } <ul class="car"> @foreach (var item in modelCoun ...

I need assistance with an issue on my Google Dev Console, as it keeps showing an error stating that ".getcontext is

Looking for some assistance here as my development console keeps displaying an error: Uncaught TypeError: canvas.getContext is not a function. Here is the problematic code snippet: `var canvas = document.createElement; var c = canvas.getContext("2d&qu ...

The child component is experiencing issues with receiving props from the father component, even though it is functioning

After successfully passing data from the father component to the child and displaying it in the view, everything seemed to be working fine at first. However, upon checking the console, I noticed that there was an issue occurring, even though the code appea ...

Change from full manual control to automatic mode

Here is the link to my code: http://jsfiddle.net/yHPTv/2491/ I am experiencing an issue with the transition effect. The hidden element is supposed to slide into view from the right edge of the .block element, but instead, it just appears suddenly. .blo ...

Implementing dropdown filtering for nested ng-repeats in Angular application

I currently have the following data structure set up: vm.years = [{ year: number, proevents: [{year: number, division: string, level: string, place: string, names: string}], nonproevents: [{year: number, division: string, level: string, place: st ...

AngularJS is having trouble passing data to phpMyadmin's mySql database

I'm a beginner with AngularJS and it seems like I'm having trouble inserting data into my database. I've tried following a few instructions but it doesn't seem to be working. When I click on the submit button, nothing happens and no dat ...

Prevent the execution of useEffect on the client side in Next JS if the data has already been retrieved from the server

Upon loading the server side rendered page, data is fetched on the server and passed to client side components. To handle this process, a hook has been created with a state that updates based on checkBox changes. When the state changes, a useEffect is tri ...

Adjusting the field of view of a perspective camera in THREE.JS while maintaining the camera's original distance

My ultimate goal is to adjust the FOV value of my camera while triggering an animation. However, upon implementing the FOV value changes, I notice that my scene appears smaller. This has led me to question the mathematical relationship between the FOV val ...

Ways to specify the default value for a component

A sample of my custom component code (Amount.tsx) is shown below: const Price = ({ price, prevPrice }) => { return ( <div className="product-amount"> <div className="price"> {prevPrice ? (<del class ...

What is the best way to swap out every instance of an array?

There are two arrays that I'm working with, The first array is defined as var symbols = ['A', 'B'];, and the second array is defined as var num = ['3', 'A', '5', '4']; I am looking for a so ...

Finding the Row Number of an HTML Table by Clicking on the Table - Utilizing JQuery

Seeking assistance to tackle this issue. I currently have an HTML table with a clickable event that triggers a dialog box. My goal is to also retrieve the index of the row that was clicked, but the current output is not what I anticipated. //script for the ...

Incorporate a link to an image following a click event toggle using Jquery

I managed to create a code snippet that toggles between two images when clicked, thanks to some assistance from stackoverflow. However, I am now looking to add a link to the second image that redirects users to another webpage, like The App Store. My ques ...