AngularJS - 基于另一个变量动态更改变量

时间:2014-09-19 19:16:44

标签: angularjs dynamic

我正在试图弄清楚如何使用一组if-else语句使用Angular JS动态更改DOM中的值。

我想要更改的值是 basketballpayout.basketballpay ,具体取决于团队总薪水的价值( payout.grossprod

以下是代码:

<html>
<head>

    <link rel="stylesheet" type="text/css" href="index.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
    <script src="script.js" type="text/javascript"></script>
</head>
<body  ng-app="Payout">
<form novalidate ng-controller="PayoutCtrl">
    ENTER YOUR TEAM'S TOTAL SALARY <input type="text" name="Gross Production" placeholder="$"  ng-model="payout.grossprod"><br />
    ENTER YOUR CURRENT TEAM'S NET PAYOUT ACCOUNT <input type="text" name="Net Payout" placeholder="%"  ng-model="payout.currentpay"><br />
    <p >Current Payout: {{payout.currentpay}} %</p>
    <p>Current Yearly Compensation: {{payout.grossprod * payout.currentpay / 100 | currency }}</p><br />
    <p>basketball Payout: {{basketballpayout.basketballpay}} %</p>


</form>

var app = angular.module("Payout",[]);
app.controller("PayoutCtrl", function($scope) {
    $scope.payout= {currentpay: 0, grossprod: 0};
    $scope.basketballpayout= {basketballpay: "", basketballcom: 0, basketballdif: 0};

if ($scope.payout.grossprod === 0){ 
    $scope.basketballpayout.basketballpay="0";
    percent = 0;    
} else if ($scope.payout.grossprod < 175000){ 
    $scope.basketballpayout.basketballpay="20";
    percent = 0.20;
} else if ($scope.payout.grossprod < 200000){ 
    $scope.basketballpayout.basketballpay="25";
    percent = 0.25;
} else  {
    $scope.basketballpayout.basketballpay="60";
    percent = 0.60;
}

});

2 个答案:

答案 0 :(得分:3)

只需将视图绑定设置为function调用而不是属性,并让该函数执行所需的计算。

Live Demo

<p>{{ foo() }}</p>

JS:

$scope.foo = function() {
  //calculate and return the desired binding
  return $scope.bar * $scope.baz;
};

您遇到的另一个问题是您将字符串与数字进行比较。您应该使用type="number",或者您可以使用myNumber = parseInt($scope.myProp, 10)来获取数字而不是字符串。

答案 1 :(得分:0)

这是一个选择输入如何依赖于另一个选择输入的示例。 enter image description here

<md-select name="inputName" ng-model="inputModel" 
    ng-change="anotherInputModel = (inputModel == 'Some Value') ? 'value of anotherInputModel' : (inputModel == 'Some other value') ? Some Another Value : ''>
    <md-option ng-value="val.value" ng-repeat="val in val">
        {{val.value}}
    </md-option>
</md-select>

<md-select name="anotherInput" ng-model="anotherInputModel">
    <md-option ng-value="value.value" ng-repeat="value in Values">
        {{value.name}}
    </md-option>
</md-select>