How can you calculate the ratio of one property value to another in AngularJS?

In my code, I am using ng-repeat to display data values from an object.

<div ng-controller="myctrl">
  <ul ng-repeat="number in numbers">
    <li><span ng-bind="number.first"></span></li>
    <li><span ng-bind="number.second"></span></li>
    <li><span ng-bind="number.third"></span></li>
  </ul>
</div>

However, one of the property values in the object is dependent on the value of other properties (I want the value of third to be equal to first divided by second).

.controller('myctrl', function($scope) {

    $scope.numbers = [
        {
        first: 8,
        second: 5,
        third: ? // (I need this to be first / second)
        },

        {
        first: 4,
        second: 5,
        third: ? // (I need this to be first / second)
        }
  ];

});

I am struggling with setting this up correctly as I find it harder than expected. It's been a while since I worked with AngularJS or JavaScript, so chances are I have approached the ng-repeat incorrectly.

Answer №1

To achieve this functionality, you can either perform the division in the view by dividing the first key with the second (

<li><span ng-bind="number.first/number.second"></span></li>
), or utilize a getter in the controller.

A getter is a method that retrieves the value of a specific property.

var myApp = angular.module('myApp', []);

myApp.controller('MainController', function($scope) {
  $scope.numbers = [{
    first: 8,
    second: 5,
    get third() {
      return this.first / this.second
    }
  }, {
    first: 4,
    second: 5,
    get third() {
      return this.first / this.second
    }
  }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app='myApp' ng-controller="MainController">
  <ul ng-repeat="number in numbers">
    <li><span ng-bind="number.first"></span>
    </li>
    <li><span ng-bind="number.second"></span>
    </li>
    <li><span ng-bind="number.third"></span>
    </li>
  </ul>
</body>

Fiddle Demo

Answer №2

In case the third number in the object is not required and can be null or completely omitted, you can handle it as follows:

$scope.numbers = [
  {
    first: 8,
    second: 5,
    third: null /* unnecessary property */
  },
  {
    first: 4,
    second: 5,
    third: null
  }
];

<ul ng-repeat="number in numbers">
  <li><span ng-bind="number.first"></span></li>
  <li><span ng-bind="number.second"></span></li>
  <li><span ng-bind="(number.first / number.second)"></span></li>
</ul>

Answer №3

give this a shot

let application = angular.module("application",[]);

application.controller("mycontroller" , function($scope){
  
$scope.variables = [
        {
        value1: 8,
        value2: 5,
      
        },

        {
        value1: 4,
        value2: 5,
      
        }
];

});

   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
   

  
  <body>   
<div ng-app="application">       
<div ng-controller="mycontroller">
     <ul ng-repeat="variable in variables">
      <li><span ng-bind="variable.value1"></span></li>
      <li><span ng-bind="variable.value2"></span></li>
      <li><span ng-bind="variable.value1 / variable.value2"></span></li>
    </ul>
    </div>
  </div>

  </body>
  
  
</html>

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

How can I prevent the state from being overridden in the reducer function when updating the State Context API?

I'm currently facing an issue with my reducer case where it ends up overwriting the passed id instead of simply adding to the existing array of ids. Can you enlighten me on the fundamental concept behind state copying and clarify when to utilize the s ...

What is the method for dividing a string using capital letters as a delimiter?

I am currently faced with the challenge of splitting a string based on capital letters. Here is the code I have come up with: let s = 'OzievRQ7O37SB5qG3eLB'; var res = s.split(/(?=[A-Z])/) console.log(res); However, there is an additional re ...

In order to display the particle-slider logo effect, the JavaScript on the page needs to be refreshed

I have a website frontend integrated from WordPress using an HTML 5 Blank Child Theme. The site features a logo effect utilizing particle slider for screen sizes greater than 960px, and a flat logo image for screen sizes less than 960px. Everything works p ...

Traverse a computed attribute in Vue.js

I am working with a component that contains a simple array as its data: data() { return { roles: [ { id: '1' , name: 'admin'}, { id: '2' , name: 'user'}, { id: &a ...

Retrieve the native interface from the Puppeteer browser/page context

Can a native interface be obtained from the Browser or Page instance to verify if an object is an instanceof this interface? For example, in a testing scenario with jest (where CanvasRenderingContext2D is not available due to being a Node context rather t ...

Modify the readonly property of an input element in ReactJS

I am looking to manipulate attributes on an HTML input element. Here is what I have attempted: constructor(props) { super(props); this.state = {inputState: 'readOnly'}; } And within the render function: <input className="form-contr ...

Submitting a JSPX form to interact with PHP backend

Can a JSP/JSPX form be used to submit data to a PHP file? The PHP file will handle validation and database updates, then send a response back to the same JSP/JSPX form. The process should be done using AJAX with jQuery. What steps are involved in achievi ...

Sharing server object in expressJS with another file through module.exports

As I work on my expressJS app, I encountered a situation where I needed to share the server object with another file. To achieve this, I decided to create the server in my app.js file and then expose it to one of my routes. var server = http.createServer( ...

Error encountered: The module '@mui/x-data-grid' does not export 'GridActionsCellItem'

I'm facing an issue while trying to import 'GridActionsCellItem' from '@mui/x-data-grid'. Here's the code: import { GridActionsCellItem } from '@mui/x-data-grid'; An error message pops up indicating: Attempted impor ...

How can I troubleshoot the unresponsive remove div function on my website?

My code is running fine on CodePen (link provided below), but for some reason, it's not working properly in the web browser. I am executing the code from localhost and the button isn't responding as expected. CODE Here is my Visual Studio code ...

Transmitting Various Static Files via Express Router

I am currently utilizing the Express router to serve static .html files based on the URL specified in router.get. For example, this code snippet sends the homepage: router.get('/', function(req, res, next) { res.sendFile('index.html&ap ...

Is requesting transclusion in an Angular directive necessary?

An issue has cropped up below and I'm struggling to figure out the reason behind it. Any suggestions? html, <button ng-click="loadForm()">Load Directive Form</button> <div data-my-form></div> angular, app.directive(&apos ...

Issue with calling function from props in React is not being resolved

There seems to be an issue with the function not being called when passed into a functional component. While the onSubmit function is triggered, the login(email, password) function inside the Login component is never executed. Despite placing console.log s ...

Enable vertical scrolling on the second row of a table while keeping the first row fixed as the table header (CSS)

While embedding the Ace Editor in a Chrome popup window, I encountered a challenge. My goal was to keep the first row of text always visible at the top while allowing the rest of the Editor to fill the screen. However, there is an issue with a vertical scr ...

What is the best method for launching a new window or tab in AngularJS?

My ASP.NET application incorporates AngularJS, however, we are facing an issue where clicking on "edit" opens the new view in the same tab. Is there a way to open it in a new tab instead? Here's the code snippet: List.html: <td><a ng-click= ...

Can you explain the contrast between the functions 'remove' and 'removeChild' in JavaScript?

I have recently coded an HTML page in order to gain a better understanding of how element removal functions. Code: <html> <head> <script> var childDiv = null; var parent1 = null; var parent2 = null; function ...

What is the proper way to incorporate a ref within a class component?

I am encountering an issue with my class component. I'm wondering if there is a comparable feature to useRef() in class components? Despite several attempts at researching, I have yet to find a solution. ...

The Flask CORS issue arises from the absence of the Access-Control-Allow-Origin header when using the redirect() function

I am currently working on setting up OAuth Twitter User-sign in using Flask API and Angular. Every time I click the sign in with Twitter button and a pop-up window opens, I encounter the following error message: XMLHttpRequest cannot load https://api.twi ...

What is the best way to pass multiple parameters along with the context to a URL in Vuex?

Link to StackBlitz I am currently working on how to send multiple action parameters with context to a URL. I have been encountering a 400 error in my attempts. The selectedPoint and departurePoint are coming from child components and stored as variables i ...

TS2307 Error: The specified module (external, private module) could not be located

I have come across similar queries, such as tsc throws `TS2307: Cannot find module` for a local file . In my case, I am dealing with a private external module hosted on a local git server and successfully including it in my application. PhpStorm is able ...