Issue with data-ng-class function not being invoked

I'm currently working on a simple Angular project where I need to dynamically color list items based on a function called in data-ng-class.

Below is an excerpt from my HTML file:

<div>
    Rooms:<ul style="list-style:none;">
        <li style="display:inline-block; padding:20px;" 
            data-ng-repeat="room in SingleDetailedCtrl.singleRooms"
            data-ng-class="getClass('room')">
                {{ room }}
        </li>
    </ul>

    To return back, please <a ui-sref="plan">click here</a>
</div>

The respective controller code snippet:

myApp.controller("SingleDetailedController", function ($log) {
    var singleSelf = this;
    this.singleRooms = ["f1-101", "f1-110", "f2-203", "f3-321", "f3-302"];
    this.sa = ["f1-101", "f2-203", "f3-302"];
    this.sna = ["f1-110", "f3-321"];
    
    this.getClass = function (room) {
        console.log("sdc");
        var color = red;
        
        angular.forEach(singleSelf.singleRooms, function (value, key) {
            if (value == room) {
                console.log("sdc if");
                color = green;
            }
        });
        return color;
    };
});

I seem to be facing an issue where the expected console output is not being generated. It appears that the getClass() function might not be getting called as intended.

Despite reviewing similar questions regarding this problem, I can't seem to identify where the issue lies within my code.

Your assistance in resolving this matter would be greatly appreciated.

Answer №1

In order to display the rooms, make sure you are using the controller instance SingleDetailedCtrl along with the specified method.

<li style="display:inline-block; padding:20px;" 
    data-ng-repeat="room in SingleDetailedCtrl.singleRooms"
    data-ng-class="SingleDetailedCtrl.getClass('room')">
{{ room }}
</li>

Answer №2

There are a few minor mistakes that need addressing.

  • The main error lies in using colons instead of commas for the room parameter when passing it to the getClass method in data-ng-class.
  • Furthermore, the color red should be defined as a string.

To rectify these issues, here is an updated and functional code snippet. (I apologize for cluttering $scope with everything as passing the controller instance around unnecessarily complicates things)

angular.module("app", [])
  .controller("SingleDetailedController", function($log, $scope) {
    var singleSelf = this;
    $scope.singleRooms = ["f1-101", "f1-110", "f2-203", "f3-321", "f3-302"];
    $scope.sa = ["f1-101", "f2-203", "f3-302"];
    $scope.sna = ["f1-110", "f3-321"];
    $scope.getClass = function(room) {
      console.log("sdc");
      var color = "red";

      angular.forEach($scope.sna, function(value, key) {
        if (value == room) {
          color = "green";
        }
      });
      
      return color;
    };

  });
.red{
  background-color: red;
} 


.green{
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="SingleDetailedController">
  Rooms:
  <ul style="list-style:none;">
    <li style="display:inline-block; padding:20px;" data-ng-repeat="room in singleRooms" data-ng-class="getClass(room)">
      {{ room }}
    </li>
  </ul>

  To go back <a ui-sref="plan">click here</a>
</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

Encountering a roadblock while trying to work with AngularJS Material radio buttons

In one of my projects, I have implemented a polling system where users can choose a question from a list and then proceed to the options page. On the options page, users can select their answer choices and submit their responses. The results are then displ ...

Struggling to get this bootstrap carousel up and running

I can't seem to get this bootstrap carousel to switch slides, whether I use the indicators or arrows. My other carousel works perfectly fine and I've added all necessary Bootstrap and JavaScript CDNs. I'm puzzled as to why it's not func ...

Creating packaging for a node-webkit application

https://github.com/rogerwang/node-webkit/wiki/How-to-package-and-distribute-your-apps When I was packaging my node-webkit application for Windows using the instructions provided in the above link, I encountered a challenge. I could not figure out how to p ...

Tips for avoiding html entities in a string

To prevent any user-entered content from being interpreted as HTML, I need to escape it so that special characters like < become < in the markup. However, I still want to wrap the escaped content with actual HTML tags. The goal is to ensure that the ...

Using Electron to redirect to a different HTML file while passing GET variables

I am currently working on developing an Electron app. Within the project files, for example, I have app.html. My goal is to send GET variables like ?id=54&q=asd to the receiver.html, where I can then retrieve these id and q variables. As we all know, ...

"Navigate back to a previous page in Vue Router without having to

I am currently exploring the option of creating a back button in my Vue.js application using vue-router that mimics the behavior of the browser's native back button. The challenge I'm facing is that when using history mode for the router and tryi ...

NodeJS: The module failed to automatically register itself

Exploring the capabilities of IBM Watson's Speech to Text API, I encountered an issue while running my NodeJS application. To handle the input audio data and utilize IBM Watson's SpeechToText package, I integrated the line-in package for streami ...

The validator function is causing an error with the 'lowerCase()' method resulting in an undefined output

Dealing with email validation in a form, I encountered a case-insensitivity issue. Using the angular validation mustMatch to ensure emails match index for index, I needed to address the case sensitivity. This led me to create the matchCaseInsensitivity fun ...

Run a script on a specific div element exclusively

Up until this point, we have been using Iframe to load HTML and script in order to display the form to the user. Now, we are looking to transition from Iframe to DIV, but we are encountering an issue with the script. With Iframe, the loaded script is onl ...

Utilizing AngularJS to iterate through an array of dictionaries

Within a specific section of my HTML code, I am initializing a scope variable like this: $scope.my_data = [ { c1: "r1c1", c2: "r1c2", c3: "r1c3", ...

What are the techniques for implementing an if statement in CSS or resolving it through JavaScript?

Demo available at the bottom of the page Within my code, there is a div called #myDiv that defaults to an opacity of 0. Upon hovering over #myDiv, the opacity changes to 1. See the CSS snippet below: #myDiv { opacity: 0; } #myDiv:hover { opacity: 1 ...

Is it possible to integrate the Firestore npm library into my Express application?

Recently, I created my own library to act as a nosql database on my node.js web server in place of mongodb. I came across this interesting quote: Applications that use Google's Server SDKs should not be used in end-user environments, such as on pho ...

Utilizing Sequelize to search for existing items or create new ones in a list

My experience with sequelize is limited and I am having trouble understanding certain aspects. Despite my efforts to search for more information, I couldn't find anything specific that addresses my confusion. // API Method function SeederApi(req: Req ...

`How can I manage my electron.js application effectively?`

As a newcomer to electron.js, I have successfully created a game using html, css, and javascript that currently runs offline on the client side. However, I am now looking for a way to access, analyze, and make changes to this app. One solution could be lo ...

What is the best way to extract data from a proxy in VUE3?

Currently, I am utilizing the ref() function to store data retrieved from Firebase. However, when attempting to filter and retrieve a single record, the outcome is not as expected. Instead of returning a single object, something different is being displaye ...

PersistJS callback function is malfunctioning

I stumbled upon a great library for managing client storage. You can find the latest version here: https://github.com/jeremydurham/persist-js However, I encountered an issue with the callback function. var result = store.get('saved_data', func ...

Choosing the perfect item with the help of a material's GridList

I've developed a react-mobx application using Material-UI, and the code structure is similar to this: render() { // defining some constants return ( <div> <img src={selectedPhoto} alt={'image title'} /> < ...

What steps can I take to make my search button work with this JavaScript code?

I am struggling with integrating my custom search bar with a JavaScript code to make it functional. Here is the code snippet for the Search Button: document.getElementById('searchform').onsubmit = function() { window.location = 'http:/ ...

Update ng-Bootstrap ToDate field by removing the date when selecting a fromDate

Is there a way to clear the date from the toDate input field while selecting a date from the fromDate input field in ng-bootstrap? <form class="row row-cols-sm-auto" *ngIf="showDateRangeImp"> <div class="col-12" ...

Exploring the Dependency Injection array in Angular directives

After some deliberation between using chaining or a variable to decide on which convention to follow, I made an interesting observation: //this works angular.module("myApp", []); angular.module('myApp', ['myApp.myD', 'myApp.myD1&a ...