Problem with ng-model in logic

I am facing a small problem with an ng-model that I have been working on.

First, let me show you the part where the ng-model is functioning correctly:

<input type="text"
         ng-model="slip.risk"
         ng-change="riskWinCalculations(slip, 'RISKSTRAIGHT')">

  <input type="text"
         ng-model="slip.win"
         ng-change="riskWinCalculations(slip, 'WINSTRAIGHT')">

  <strong>To Win: </strong>{{straightTotalWin | currency}}

  <strong>Total Stake: </strong>{{straightTotalStake | currency}}

Now, moving on to the HTML section where the ng-model is causing issues for me:

<input type="text"
         ng-change="riskWinCalculations(null, 'RISKPARLAY')"
         ng-model="riskParlay">

  <strong>To Win: </strong>{{winParlay | currency}}

  <strong>Total Stake: </strong>{{riskParlay | currency}}

In this controller, there are functions named applyParlayRisk and riskWinCalculations, where the case RISKPARLAY is posing problems. The other cases are functioning perfectly fine.

   applyStraightRisk = function(slip) {
      var moneyLine = _.result(_.find(slip.lines, {isSelected: '1'}), 'moneyLine');
      slip.win = RiskWikCalculations.calculateStraightBet(slip.risk, parseFloat(moneyLine, 10), true);
    }, 

   applyStraightWin = function(slip) {
      var moneyLine = _.result(_.find(slip.lines, {isSelected: '1'}), 'moneyLine');
      slip.risk = RiskWikCalculations.calculateStraightBet(slip.win, parseFloat(moneyLine, 10), false);
    }, 

   applyParlayRisk = function(parlay, riskParlay) {
      $scope.riskParlay = riskParlay;
      console.log($scope.riskParlay);
      //this logs UNDEFINED
      $scope.winParlay = riskParlay * (parlay.payoutProportion || 4.5);
    }, 

  sumStraightStakes = function(betSlip) {
      var totalStake = 0,
          totalWin = 0;
      _.each(betSlip, function(slip) {
        if (slip.risk) {
          totalStake += parseFloat(slip.risk, 10);
        }
        if (slip.win) {
          totalWin += parseFloat(slip.win, 10);
        }
      });
      $scope.straightTotalStake = totalStake;
      $scope.straightTotalWin = totalWin;
    };


    $scope.riskAll = 0;
    $scope.winAll = 0;
    $scope.riskWinCalculations = function(slip, type) {
    switch (type) {
      case 'RISKSTRAIGHT':
        applyStraightRisk(slip, slip.risk);
        break;
      case 'WINSTRAIGHT':
        applyStraightWin(slip, slip.win);
        break;
      case 'RISKPARLAY':
        applyParlayRisk($scope.currentParlay, $scope.riskParlay);
        break;
     }
     sumStraightStakes($scope.betSlip);
    };

Can you point out where you think the mistake might be in my code?

UPDATE

I have implemented the same functionality in a mobile app, and it is working properly there. Here's a look at how it's done:

HTML:

<button ng-click="openRiskWinKeypad(null, 'RISKPARLAY')">
     Risk: {{riskParlay}}
  </button>

  <strong>Total Stake: </strong>{{riskParlay | currency}}

  <strong>To Win: </strong>{{winParlay | currency}}

Controller:

applyParlayRisk = function(parlay, amount) {
      $scope.riskParlay = amount;
      $scope.winParlay = amount * (parlay.payoutProportion || 4.5);}

There is a slight difference here because I am opening a custom keypad for input.

$scope.openRiskWinKeypad = function(slip, type) {
      $scope.keypad = {value: 0};
      if (type === 'RISKSTRAIGHT' && slip.risk) {
        $scope.keypad.value = slip.risk;
      }
      if (type === 'WINSTRAIGHT' && slip.win) {
        $scope.keypad.value = slip.win;
      }

      $ionicPopup.show({
         // This is where the keypad opens
      }).then(function(amount) {
        if (amount) {
          switch (type) {
            case 'RISKSTRAIGHT':
              applyStraightRisk(slip, amount);
              break;
            case 'WINSTRAIGHT':
              applyStraightWin(slip, amount);
              break;
              break;
            case 'RISKPARLAY':
              applyParlayRisk($scope.currentParlay, amount);
              break;
          }
        }
        sumStraightStakes($scope.betSlip);
      });
    }; 

EDIT

If I make these changes:

<input type="text" ng-model="riskParlay"
       ng-change="riskWinCalculations(null, 'RISKPARLAY')">

and

applyParlayRisk = function(parlay, riskParlay) {
      $scope.riskParlay = riskParlay;
      console.log($scope.riskParlay);
      $scope.winParlay = riskParlay * (parlay.payoutProportion || 4.5);
    }

and

    case 'RISKPARLAY':
      applyParlayRisk($scope.currentParlay, riskParlay);
      console.log($scope.currentParlay.name);
      break;

All I receive is:

ReferenceError: riskParlay is not defined

Answer №1

Without seeing the full HTML snippet, it's difficult to say for certain, but my suspicion is that there may be an additional scope positioned between the riskParlay input and the controller. In such a scenario, the ng-model directive will likely assign the riskParlay variable to that intermediate scope rather than the controller's scope.

The reason your other inputs are functioning correctly is because they utilize object indexing in their expressions (using the . operator). When ng-model expressions employ this operator, they search up the scope hierarchy until locating a scope with the specified object. For a more comprehensive explanation of this concept, I recommend watching this informative video:

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

Elegant management of errors in a JavaScript object to prevent any occurrences of undefined errors

Often I encounter code that resembles the following hypothetical example: if (node.data.creatures.humans.women.number === Infinity) { // do-something } The issue arises when the node is undefined, causing this condition to fail. Similarly, it will fail ...

Removing the last two characters from a number with a forward slash in Vue.js

I'm encountering a slight issue with my code: <template slot="popover"> <img :src="'img/articles/' + item.id + '_1.jpg'"> </template> Some of the item.id numbers (Example: 002917/1) contain ...

"Master the art of curl login authentication with this step-by-step guide

Looking to authenticate using curl with PHP or another language For example, visit this site: When the curl site prompts for authentication as shown in the image below, how do I log in to retrieve data? https://i.sstatic.net/LGNgl.png ...

Discovering the validity of an input without using a form in AngularJS

I encountered the following issue: In my <table>, I am using ng-repeat to generate <tr> elements, each containing multiple <input> fields. It looks something like this: <table> <tr ng-repeat="plan in plans"> <td> ...

Encountered a problem when attempting to connect to a posgresql database using pg on

My experience with a PostgreSQL database has been a mix of success and frustration. I am able to connect to it and execute SQL queries using psql without any issues. However, when attempting to establish a connection with node.js using the pg client, an e ...

What could be causing the parsing issue on the page for Node.js?

When attempting to access the given page with invalid credentials: In a browser, I receive well-formatted JSON: { "error": { "code": "request_token_invalid", "message": "The access token isn't valid." } } However, trying the equi ...

Executing ts-node scripts that leverage imported CSS modules

Is there a way to execute scripts that utilize css modules? I am currently working on a typescript migration script that I would like to execute using ts-node. The ideal scenario would be to keep the script's dependencies separate from the React comp ...

Protecting an API with passport-local authentication

Let me get right to the point. I've developed a secure application using passport-local, with all routes well-covered. The purpose of my app is to retrieve data from MongoDB and serve it as an API that feeds into d3 charts. While all my webpages are s ...

Having trouble with testing axios web service promises to return results using Jest in a Vue.js application

In the process of developing a new application with Vue.js and axios, I am focusing on retrieving stock market details based on company names. To kickstart the application, I am compiling all the names of US-based S&p 500 companies into a JavaScript ar ...

Using Angular template reference variables for inputs to bind specific buttons with the same structure

Currently, I am exploring how to connect an input with a button in a row of buttons for opening images, inspired by an example shared by Mr. ruth. The layout of buttons in my web application resembles the following structure: topnav.component.html: <but ...

Establishing a constant for a JavaScript class method

Although this question may seem basic, I am struggling to grasp how this code works and felt the need to seek clarification here. Take a look at this example of a simple React component: const title = React.createElement( 'h1', {id: &apo ...

Using JQuery to visually enhance the menu selection by displaying an image and altering the background color upon hovering

Hello fellow JQuery/Javascript beginners! I recently put together a menu and wanted to add some interactive elements. Specifically, I want the background color to change when a user hovers over an item (simple enough with CSS), but I also want to include a ...

Having trouble loading an image with texture loader in Three.js? The issue may be related to the size and scale of the plane geometry

Can someone please assist me with loading images using TextureLoader? I am encountering a major issue where I am unsure how to add images to a mesh in a 1:1 scale and calculate PlaneGeometry. My goal is to display the loaded image in its original size with ...

How can we convert milliseconds to the corresponding date and time zone in Java?

1)I am trying to determine the user's timezone and current time using the following code snippets: Calendar currentdate1 = Calendar.getInstance(); TimeZone tz = Calendar.getInstance().getTimeZone(); System.out.println("time zone"+tz); System.out.pri ...

Adding a key to an uninitialized array in React JS while mapping data

I've been grappling with this code snippet for a few days now, making slow progress but still stuck. Here's the crux of the issue: My goal is to display an array of X values, all starting at 1. Someone suggested using the following code: const ...

Spinning an object smoothly in the opposite direction of the OrbitControls camera's y rotation in three.js

Is there a way to use OrbitControls in three.js to make a planeMesh always remain facing the camera? I've attempted some code but it's not quite working as expected. I want the planeMesh to slowly readjust its orientation only when the camera mov ...

The jquery validation engine's scroll feature is not functioning properly when used in conjunction with

jquery validation engine with the option scroll set to false is functioning properly without using 'validate' as shown below... jQuery('#form').validationEngine({scroll: false}); However, it does not work when I use it like this. jQue ...

Encountered difficulties logging in with MongoDB and Node.js

I encountered an issue while attempting to authenticate a user using MongoDB and Node.js. Although no errors are thrown, the system fails to provide the expected data after the user logs in. Below is a breakdown of my code. server.js var port=8888; va ...

An issue has arisen with AngularJS and Twitter Bootstrap, displaying an error message stating that the function element.focus

I recently implemented the angularjs twitter bootstrap datepicker and everything seemed to be working smoothly. However, I encountered an error when trying to click on the text box for the popup datepicker. This issue has left me puzzled as I am still new ...

DataTables: Personalized Response Management

Recently I delved into AngularJS and DataTables and had a query regarding customizing the response expected by DataTables. The typical format DataTables expects looks like this: { "draw": 1, "recordsTotal": 57, "recordsFiltered": 5, "data" ...