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

The Flux Router in React Native

I am diving into the world of React Native and currently working on creating a practice app. The issue I'm facing is with the routing functionality in my project. At the moment, I have three main components: the app itself, the router component, and o ...

Extracting CSS data and storing it in a SQL database

Hello there, I've created a div using CSS like this: echo '#'. $pess2['naam'] .' { width: 190px; height: 90px; padding: 0.5em; float: left; left:'. $pess2['left'] .'px; top:'. $pess2['top'] ...

"Oops! Looks like there's a reference error - the function you're trying

Javascript: function insertSmiley(a) { var $img = $(a).children('img'); $("#message").insertAtCursor(($("#message").data("wbb").options.bbmode) ? $("#message").data("wbb").toBB($(a)): $(a).html()); return false; } HTML: <a href= ...

Analyzing and tallying JSON attributes using JavaScript

I have a JSON object with items that I need to analyze in JavaScript. When I view the JSON in the console, there is an element called items that contains an array of relevant information. console.log(json) {current_page: 1, per_page: 100, total_entries: ...

Navigate to the second level array within the JSON data structure

As someone more inclined towards design rather than programming, any assistance is highly appreciated. The main goal of this project is to create a dropdown menu using the "name" field from the JSON data and display the corresponding "stock" information wh ...

Is there a way to update the value of a variable with the help of a checkbox?

When I check the checkbox, the specOrder const gets updated as expected. However, I am struggling to figure out how to remove the value when the checkbox is unchecked. Below is the code I have been working on: const SpecialtyBurgers = () => { cons ...

Retrieve the $ionicConfigProvider within a Controller

In my controller file named ProfileController.js, I am trying to change the text of the back button. After doing some research, I found this code snippet: $ionicConfigProvider.backButton.text('Go Back').icon('ion-chevron-left'); How can ...

Unlock maximum screen viewing on your custom video player with these steps to activate fullscreen

I'm having an issue with my basic video player - when toggling fullscreen, it doesn't fill the whole screen even though I tried using .fullscreen{width:100%} without success after searching for a solution. html <div class='player-contai ...

Unlock the power of TypeScript's inheritance by utilizing static methods for type

In my TypeScript project, I have two classes: BaseModel and HotelModel. The HotelModel extends the BaseModel class, which provides static methods like findById, all, etc. export default class BaseModel { private collection:string _id:string | undefine ...

Anticipate that the function parameter will correspond to a key within an object containing variable properties

As I develop a multi-language application, my goal is to create a strict and simple typing system. The code that I am currently using is as follows: //=== Inside my Hook: ===// interface ITranslation { [key:string]:[string, string] } const useTranslato ...

JavaScript's setAttribute function is not functioning as expected

I have been using the setAttribue method as shown below. It works perfectly for the first instance, but after that, when I try to change the value, it displays an alert without updating with document.getElementById("to").setAttribute("value", selValue); d ...

JavaScript array as a reliable data storage solution

This is my unique jsp code where I am attempting to push certain data into a JavaScript array. <% int proListSize = proList.size(); ProfileDAO proDAO = null; for(int i = 0, j=1; i < proListSize; i++){ proDAO = ( ...

Assigning a Value to a Dropdown Menu in Angular

I have some JSON data that contains a True/False value. Depending on whether it is true or false, I want a specific option in a Select Dropdown to be automatically selected. This is the HTML code using Angular 16: <select name="reportNo" id=& ...

Discovering more about this topic

Looking for a way to create an expandable box that enlarges when "read more" is clicked, revealing text below it. And also looking to add a button that closes the expanded text back up. Experimented with the toggletext JavaScript command, as found on this ...

Nuxt - Dynamically manage routes while utilizing server-side rendering functionality

Hello! I have a question for you: I have: a Nuxt app set up with target: 'server' in the nuxt.config.js an API that provides me with a template associated with a given path (for example, /person/maxime will return template: PersonsSingle) a vue ...

What is the best way to manipulate and update individual counters in React components?

I developed a ticket ordering system for a project, but encountered an issue where increasing the quantity of one ticket also resulted in the incrementation of the other ticket's counter. I suspect this occurs because only one value is stored in the s ...

Tips on how to render a component only after receiving an AJAX response

I'm encountering an issue with one of my React components. It seems like AJAX is not fetching all the content from the external server before React renders the ChildComp component. https://i.stack.imgur.com/o0ZtH.png Above, you can view the tree of ...

Error encountered when trying to load Ajax script

As a beginner in the learning process, my code may appear messy. I am currently wrapping up my second project, which is a photo viewer. On the main page, there is a navigation system that loads different sections of the website using ajax. Since this proje ...

The basic jQuery script seems to be malfunctioning

I am trying to attach an on click event to an li element using jQuery. I have written a simple jQuery code within the document ready function, but for some reason it is not functioning as expected. I have checked in both Chrome and Firefox, and there are n ...

How can you store previously calculated values in a costly recursive function in a React application?

Consider a scenario where there is a recursive callback function like the one shown below: const weightedFactorial = useCallback(n => { if (n === 0) { return 1; } return weight * n * weightedFactorial(n - 1); }, [weight]); Is it possible to ...