Ways to set a default value in AngularJS when there is no value to compare in an array

Hello, I'm a newcomer to AngularJS and I have the following code snippet in HTML:

// Here, I have another ng-repeat loop where I compare home.home_info_id with avg.home_inof_id
<div ng-repeat='home in homeDetailInfo'>
    <div ng-repeat="avg in homerating">
      <div ng-if="avg.home_info_id==home.home_info_id">
        <div class="star" ng-modal="avg" data-score="{{avg.avg}}"></div>
      </div>
    </div>

I am getting the following data:

hallrating=[
{"home_info_id":"94","avg":"3.33333333333333"},
{"home_info_id":"119","avg":"4"},
{"home_info_id":"95","avg":"4.5"}
]

It works perfectly for three homes, but the issue arises with the fourth home as it has not been rated yet. I need to display data-score='0' for that home. I have attempted the following:

<div ng-repeat='home in homeDetailInfo'>
        <div ng-repeat="avg in homerating">
          <div ng-if="avg.home_info_id==home.home_info_id">
            <div class="star" ng-modal="avg" data-score="{{avg.avg}}"></div>
          </div>
         <div ng-if="avg.home_info_id!=home.home_info_id && avg.avg!=''">
            <div class="star" ng-modal="avg" data-score="0"></div>
          </div>
        </div>

This did not work for me so I also tried:
<div ng-repeat='home in homeDetailInfo'>
        <div ng-repeat="avg in homerating">
          <div ng-if="avg.home_info_id==home.home_info_id">
            <div class="star" ng-modal="avg" data-score="{{avg.avg}}"></div>
          </div>
         <div ng-if="!avg.avg">
            <div class="star" ng-modal="avg" data-score="0"></div>
          </div>
        </div>

Answer №1

A method can be created for this purpose.

$scope.displayResult = function(result) {
    if (angular.isDefined(result)) {
        return result;
    } else {
        return 0;
    }
}

After creating the method, it can be used in HTML like this:

<div class="star" ng-modal="average" data-result="displayResult(average.result)"></div>

Please note the correction: I missed adding () around average.result.

Answer №2

<div ng-repeat=' house in houseDetails'>
  <div class="rating-star" data-score="{{ calculateScore(house.house_id) }}"></div>
</div>

Next, in your angular controller

$scope.calculateScore = function (houseId) {
  var score = 0;

  houseratings.forEach(function (rating) {
    if (rating.house_id === houseId) {
      score = rating.average_score;
    }
  }

  return score;
};

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

Validation of Regular Expressions in Javascript

I am trying to implement control validation using Javascript. The validation criteria states that the number should consist of a maximum of 12 digits, with the first 7 being '9900000' followed by either a '0' or a '1', and en ...

What makes Angular date pickers sluggish?

Have you ever noticed that Angular JS date pickers consume a lot of CPU? When multiple date pickers are present on a page, they can noticeably reduce the site's speed. Is there a way to minimize this issue? Take for example the official Angular for ...

What is the best way to close an ajax page within the main page using a button?

I am dealing with a situation where I have 2 pages. The first page contains a div called 'ajaxicall', which loads another page inside it. The challenge I am facing is figuring out how to close the second page when I click on the "close" button w ...

Guide to delivering a PDF document from a controller

In my pursuit to send a PDF file from a Controller Endpoint using NestJs, I encountered an interesting issue. Without setting the Content-type header, the data returned by getDocumentFile function is successfully delivered to the user. However, when I do ...

Strategies for maintaining pristine Firebase child paths

I have a list of data that I want to structure in Firebase. However, I encountered an error: Error: Firebase.child failed: The first argument provided is not a valid path. Path names should not include ".", "#", "$", "[", or "]" characters and must be no ...

Toggle visibility of multiple DIVs with identical classes using radio buttons

I'm looking to streamline my use of radio buttons in HTML. How can I implement a single set of radio buttons at the top that will toggle the visibility of all DIVs with the same class on my webpage? <form> <input type="radio" name="csr_sel ...

Customize the text color of the active tab in Material-UI Tabs

I am facing a situation where I have this specific object: const tabStyle = { default_tab:{ color: '#68C222', width: '33.3%', backgroundColor: '#FFFFFF', fontSize: 15 }, active_tab: ...

Troubleshooting issue with Onchange in select HTML element within Django

I'm working with a Problems model in my project. In my Models file models.py class Problems(models.Model): Easy = 'Easy' Medium = 'Medium' Hard = 'Hard' NA = 'NA' DIFFICULTY = [ (NA ...

React component is unable to identify prop

I'm attempting to send an array of objects from the main App.js file to a smaller component using props. However, for some reason, the prop is not being recognized within the smaller component file. https://i.stack.imgur.com/WuyFr.png https://i.stac ...

The registration form's captcha did not prevent the submission of incorrect captchas

This is a PHP register.php page <?php require_once 'config.php'; ?> <?php if(!empty($_POST)){ try { $user_obj = new Cl_User(); $data = $user_obj->registration( $_POST ); if($data)$succ ...

Transferring data from SocketIO to Vue.js

Is there a way to effectively transfer data results received from socketIO to the Vue instance? Below is my current code implementation: let socket = io(); let users; socket.on('user-connected', (data) => { users = data.count; }); socket ...

Manually initializing Angular bootstrap with async in the Angular script tag

I am encountering an issue when trying to asynchronously download the Angular script in my application and manually bootstrap the application upon loading. The error message states: Failed to instantiate module wt due to: Error: [$injector:modulerr] htt ...

"Utilize PHP to access an object's properties in a manner similar to an array

Consider the JSON object presented below: $json = '{ "Name": "Peter", "countries": { "France": { "A": "1", "B": "2" }, "Germany": { "A": "10", "B": "20" }, .... } }'; I am looking for a way to ...

Node.js Express JS is currently in the process of retrieving a file

I'm currently grappling with an issue while attempting to download a file using express js. Here is the function in question: var download = function(uri, filename, callback) { request .get(uri) .on('response', function (response) { ...

Looking for a seamless way to convert jsp code to html using sightly in AEM 6.1?

I need help transforming JSP code to HTML using Sightly in AEM. In the JSP code, we have a scriptlet that stores a value from the dialog into a JSP variable called "coltype" using the code pageContext.setAttribute("coltype", xssAPI.filterHTML(properties. ...

Unable to designate the drop-down option as the default selection

Can anyone help me with setting a default drop-down value using JavaScript? I have been struggling to achieve this. You can find my code on jsFiddle <div ng-controller="csrClrt"> <div ng:repeat="(key, item) in items track by $index"> ...

How can CSS positioning be utilized to align lines accurately?

Recently, I created a basic jsbin to draw a line connecting two points. It doesn't rely on any drawing libraries; just plain JavaScript and jQuery. I managed to calculate the angle using code I found in this library. When dragging the circle at the ...

Running cy.task after all test suites can be done by adding the task in a

I need some guidance on running cy.task after executing all test suites. I have a file generated at the start of the tests that I would like to remove once they are completed. Regardless of whether any tests passed or failed, I want to trigger cy.task im ...

Exploring the Validation of POST Requests with JSON Content

When working with NodeJS and Express 4, I often come across situations where the client sends JSON data that needs to be processed: { "data" : "xx" "nested" : { field1: "111", field2: "222" } } However, on the server side, I ...

Sometimes Ionic fails to display the list items

I am encountering an unusual issue with a mobile application that has been created using Meteor, Angular, and Ionic. Within one of the tabs, I am subscribing to a collection called Contacts and displaying the contact list using an ionic list: <ion-lis ...