尝试使用相同的逻辑创建两个控制器。当我为每个var使用单独的函数时,它可以工作。但是当我尝试将var作为参数传递时,它什么都不做。
代码在这里:
function Ctrl($scope) {
$scope.Score1 = 0;
$scope.Score2 = 0;
$scope.add_btn = function(num) {
$scope.num ++;
};
$scope.dist_btn = function(num) {
if ($scope.num > 0) {
$scope.num --;
} else {
$scope.num = 0;
}
};
}
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<style>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(Score1)">+</button>
<input type="text" value="{{Score1}}">
<button ng-click="dist_btn(Score1)">-</button>
<button ng-click="add_btn(Score2">+</button>
<input type="text" value="{{Score2}}">
<button ng-click="dist_btn(Score2)">-</button>
</div>
</div>
答案 0 :(得分:1)
您可以在不使用任何数组的情况下使用此逻辑,您使用$ scope.num但它在作用域上创建了一个新变量,因此失败。这样可以正常使用
function Ctrl($scope) {
$scope.Score1 = 0;
$scope.Score2 = 0;
$scope.add_btn = function(num,from) {
num ++;
if(from == 1)
$scope.Score1 = num;
else
$scope.Score2 = num;
};
$scope.dist_btn = function(num,from ) {
if (num > 0) {
num --;
} else {
num = 0;
}
if(from == 1)
$scope.Score1 = num;
else
$scope.Score2 = num;
};
}
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<style>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(Score1,1)">+</button>
<input type="text" value="{{Score1}}">
<button ng-click="dist_btn(Score1,1)">-</button>
<button ng-click="add_btn(Score2,2)">+</button>
<input type="text" value="{{Score2}}">
<button ng-click="dist_btn(Score2,2)">-</button>
</div>
</div>
答案 1 :(得分:0)
$scope.num // find num inside #scope
$scope[num] // find the member inside scope variable with the value of num (Score1 in your case)
也会从元素中发送参数:
<button ng-click="add_btn('Score1')">+</button>
而不是num请重构为id或其他.. 简而言之:
$scope.add_btn = function(id)
{
$scope[id]++;
};
答案 2 :(得分:0)
简单而肮脏的解决方案:)
可能有更好的东西
function Ctrl($scope) {
$scope.Score = [0, 0];
$scope.add_btn = function(num) {
$scope.Score[num]++;
};
$scope.dist_btn = function(num) {
if ($scope.Score[num] > 0) {
$scope.Score[num]--;
} else {
num = 0;
}
};
}
&#13;
</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ -->
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<style>
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<div ng-app>
<div ng-controller="Ctrl">
<button ng-click="add_btn(0)">+</button>
<input type="text" value="{{Score[0]}}">
<button ng-click="dist_btn(0)">-</button>
<button ng-click="add_btn(1)">+</button>
<input type="text" value="{{Score[1]}}">
<button ng-click="dist_btn(1)">-</button>
</div>
</div>
&#13;