A simple way to retrieve the computed value from one ng-model and assign it to a different ng

I am facing an issue where I have 3 ng-models and I need to fetch calculated data from the first two into the third one using angularjs

I attempted a solution but it doesn't seem to work as expected

Below is the HTML code snippet:

var urlt = 'http://localhost/tripsheets';
app.factory('tripsheetFactory', function ($http) {
  return {
    getTripsheets: function () {
      return $http.get(urlt + '/all');
    },
    addTripsheet: function (tripsheet) {
      return $http.post(urlt, tripsheet );
    },
    deleteTripsheet: function (tripsheet) {
      return $http.delete(urlt + '?id=' + tripsheet.id);
    },
    updateTripsheet: function (tripsheet) {
      return $http.put(urlt + '?id=' + tripsheet.id, tripsheet);
    }
  };
});

app.controller('TripsheetCtrl', function ($scope, tripsheetFactory) {

  $scope.tripsheets = [];
  $scope.getTotalCalc = function () {
    return $scope.tripsheets.cash * $scope.tripsheets.tax;
  };

  tripsheetFactory.getTripsheets().then(function(data){
    $scope.tripsheets = data.data;
    $scope.tripsheet = {
      tripsheet_num: $scope.tripsheets.length +1,
      cash:null,
      tax:null,
      total: $scope.getTotalCalc()
    };
  });
}); 

Answer №1

Have you ever thought about using a watch function on the tripsheet object to calculate a specific value?

$scope.$watch('tripsheets', function(val){
    $scope.tripsheets.total = $scope.tripsheets.cash*$scope.tripsheets.tax;
  }, true);

To see a sample demo, check out: http://plnkr.co/edit/Ml6eLM4vCYz3tPaL8j3n?p=preview

Answer №2

If you prefer, you have the option to set a watch on the overall amount...

$scope.$watch(function() {
    return $scope.tripsheets.cash * $scope.tripsheets.tax;
 }, function(value) {
    $scope.tripsheets.total = value;
});

Interactive Example

Alternatively, you can utilize Object.defineProperty() (which requires ES5 or later)...

Object.defineProperty($scope.tripsheets, 'total', {
    get: function(){
        return $scope.tripsheets.cash * $scope.tripsheets.tax;
    }
});

Live Demo

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

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

Obtaining content from a URL based on the client's IP address rather than the server's address

Is there a way to retrieve the content of a URL from another site using a client's IP address instead of the server's? I attempted this in PHP but was unsuccessful. Below is the code snippet I tried: <?php $homepage = $_SERVER['REMOTE_A ...

Exploring the practical applications of Jade template along with AngularJS

I'm currently working on a website project with Node.js and Express. I need help making the divisions on the page dynamic. Is Jade the best tool for this, or is there another method I should use? Also, what exactly is AngularJS used for? I've tri ...

Is it possible to utilize Angular.js as a full substitute for a traditional JavaScript template engine?

While angular excels in two-way data binding and single-page applications, could it also serve as a viable replacement for a JavaScript template engine? Let's dive into the potential pros and cons of this approach. ...

Can the garbage collector in Typescript/JavaScript effectively handle circular references, or does it result in memory leaks?

When working in languages such as C#, managing memory is not a problem. However, this can lead to difficult-to-find memory bugs in other languages. Is it safe to use the following code snippet in Typescript or Javascript without encountering any issues? c ...

Finding the name of a particular item in an array and increasing its value - a step-by-step guide

For a homework project, I am developing a straightforward cart system. Could someone advise me on the best approach to retrieve an item from an array and increment its value by one? The array contains 25 items, each with a unique name but without any IDs a ...

Utilizing a different file to arrange and establish state

In a separate file called Origin.js, I have some data (objects) stored. This data is exported using the spread operator within an object named OriginState: Origin.js //info const info = { title: '', year: '', }; //images const ...

Ways to modify the appearance of the button within ion-calendar

Looking to customize the styling of ion-calendar classes Attempting to add styles to the ion-calendar-month class, but not seeing any changes take effect. ...

Populate List Items until Maximum Capacity is Reached and Increase the

Is there a way to make a ListItem fill the list vertically while also being able to overflow it if needed? I'm looking for a solution that would allow me to access the height of the empty space in the list, which I believe would be the minHeight. Som ...

Summary in Javascript

After utilizing the inspect code tool in PHPStorm, I received the following message: 'recipient_user.id === app.currentUser.id ? true : false' can be simplified to '!!(recipient_user.id === app.currentUser.id)' I'm wondering: ...

The server-side PHP script may not always successfully respond to an Ajax call from the client

Whenever I try to access my index.html site, there are times when the Ajax request is made to call the PHP on the server in order to display the dynamic content. But for some reason, it only works intermittently when I manually refresh the page using the a ...

Is it possible to designate touch as the top finger and always have touch 2 be the bottom finger on the screen?

Is there a way to specify touch1 as the upper finger on the screen and always have touch2 as the lower finger, even if the lower touch is detected first? var touch1 = e.originalEvent.touches["0"]; var touch2 = e.originalEvent.touches["1"]; Can these ...

Looking for assistance with importing OBJ and MTL files into Three.js?

I'm encountering a strange issue while attempting to load an OBJ and MTL file in Three.js using the OBJMTLLoader() function and am unable to find a solution online. My project structure includes an index.html file and a js folder with all the necessar ...

Issues with implementing nested controllers for multiple $mdDialog windows in Angular Material

Apologies in advance if I am making a foolish mistake or overlooking some AngularJS logic. I am facing an issue with my custom $mdDialog which needs to open 2 different $mdDialog windows based on user selection. Everything works fine when the controllers a ...

Enhance JSON nesting with knockoutJS

I am currently working on updating a JSON object in memory using the knockout.js user interface. However, I have encountered an issue where changes made in the UI do not seem to reflect on the JSON data itself. To troubleshoot this problem, I have added bu ...

Ways to change the value of a property in reverse

I have a question about Vue and whether it is possible to achieve the opposite of using props. Let me clarify further with an example. Consider the following: const app = Vue.createApp({ data: function() { return { text: "Hello" } ...

unique map customized in a separate browser window

Attempting to complete the code provided here but encountering issues as a novice in java-scripting. It seems like the map is not loading correctly. A new tab and text are generated when DIV is created. Seeking assistance on how to open a custom map in a ...

VueJS - When using common functions, the reference to "this" may be undefined

I'm struggling to extract a function that can be used across various components. The issue is that when I try to use "this", it is coming up as undefined. I'm not sure of the best practice for handling this situation and how to properly assign th ...

Looking to set up an event listener for a customized checkbox in a Kendo UI Grid column with Vue Js?

Can someone help me figure out why my method checkboxToggle() is not working when I click on the checkbox? Here is the code snippet: ` Methods:{ toggleTemplate(){ let template = `<label class="switch" > <input type= ...

What is the best way to retrieve a style property from a <style> tag using JavaScript?

Is there a way to retrieve CSS properties set in the <style> tag in JavaScript, rather than just those set in the element's style attribute? For example: <style> div{background:red;} </style> How can I access these styles, such ...