使用角度ng-switch

时间:2018-09-20 12:57:56

标签: javascript jquery angularjs angularjs-scope

应该做什么

每个按钮都链接到一个div块(例如:button01链接到block01)。每个div块都有3个输入。最后一个输入获取其上方两个输入之间的数学函数的值。 div块必须“​​显示”不显示/隐藏。

功能

三个按钮打开三个div块的部分起作用。问题是,当我尝试在两个输入中键入内容时,最后一个输入什么也没得到。

我尝试过的

1)ng-switch和ng-switch-when

2)将div放在每个(script type="text/ng-template" id="aaa")内 然后;

var forms = ["aaa", "bbb", "ccc", "ddd"];

credit_block.displayedForms = [];

credit_block.addForm = function(formIndex) {
    credit_block.displayedForms = [];
    credit_block.displayedForms.push(forms[formIndex]);     
}

3)(这可以用,但不是我想要的)ng-show

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>


<div class="row">
			<div class="col-sm-12">
					Pick a topic:
					<label><span>Button01</span><input style="display:none" type="radio" ng-model="myVar" value="block01"></label>
					<label><span>Button02</span><input style="display:none" type="radio" ng-model="myVar" value="block02"></label>
					<label><span>Button03</span><input style="display:none" type="radio" ng-model="myVar" value="block03"></label>
			</div>
		</div>
		
		<div class="row" ng-switch="myVar">
			<div class="col-sm-12" ng-switch-when="block01">
				<h3>Cumpar locuinta</h3>
				<div class="row">
					<div class="col-sm-10 col-xs-8 number-box">
						<label>Sum:</label>
						<input class="button-option" type="number" ng-model="sum">
					</div>
				</div>
				<div class="row">
					<div class="col-sm-10 col-xs-8 number-box">
						<label>Advancement:</label>
						<input class="button-option" type="number" ng-model="adv">
					</div>
				</div>
				<div class="row">
					<div class="col-sm-10 col-xs-8 number-box">
						<label>Value:</label>
						<input class="button-option" type="number" value="{{ result() }}">
					</div>
				</div>
			</div>
  
		</div>
	</div>

<script>
	var myApp = angular.module('myApp', []);
	myApp.controller('myController', function($scope) {
		$scope.sum = 5;
		$scope.adv = 4;
        $scope.result = function() {            
                return $scope.sum - $scope.adv;
        };
    });
</script>

1 个答案:

答案 0 :(得分:0)

您遇到了一个经典的与范围相关的变量屏蔽问题。

ng-switch创建一个新范围,因此您与ng-modelsum的{​​{1}}绑定与您在{{1}中设置的绑定不对应}。

解决此新创建范围的通常方法是将adv个要绑定的属性放在对象后面,并通过该对象引用它们。

例如,在您的HTML中:

myController

然后在您的控制器中:

ng-model

Here's a demonstration of your snippet with some amendments to make it work.