如何增加和减少angularjs中的值?

时间:2014-12-01 11:34:51

标签: javascript angularjs

我最初有一个值 - 让我们称之为x。选择增量按钮应该增加“+1”值。如果我选择减量,则x应减少-1。

然而,实际发生的是当我按下增量按钮时,它会增加+1,但如果我点击减少,它会减少-2。它应该只增加/减少1个值。也不需要连续迭代(count ++和count--)。如果将“count”视为.js文件中的变量,而不是在html中将其称为ng-init =“count = 15”,那会更好。

JsBin

<div ng-controller="CounterController">
  <button ng-click="count = {{count}}+1" ng-init="count=15">
    Increment
  </button>
  count: {{count}}

  <button ng-click="count = {{(count) - 1}}">
    Decrement
  </button>
<div>

4 个答案:

答案 0 :(得分:8)

这应该可行,

<div>
    <button ng-click="count = count+1" ng-init="count=15">
        Increment
    </button>
    count: {{count}}

    <button ng-click="count = count - 1">
        Decrement
    </button>
<div>

答案 1 :(得分:3)

问题是因为你在ng-click中使用'{{',它在那里插入值,所以在角度'渲染'之后,实际代码看起来像:

<div ng-controller="CounterController">
  <button ng-click="count = 15+1" ng-init="count=15">
    Increment
  </button>
  count: {{count}}

  <button ng-click="count = 15 - 1">
    Decrement
  </button>
<div>

但你想参考。所以只需删除“{{”和“}}”即可。

答案 2 :(得分:2)

“正好增加或减少1个值”

<div ng-controller="CounterController">
  <button ng-click="increment();">
    Increment
  </button>
  count: {{count}}

  <button ng-click="decrement();">
    Decrement
  </button>
<div>

控制器:

angular.module('myApp', [])
.controller('CounterController', function($scope) {
  var incremented = false;
  var decremented = false;
  $scope.count = 15;

  $scope.increment = function() {
    if (incremented) { return; }
    $scope.count++;
    incremented = true;
  };
  $scope.decrement = function() {
    if (decremented) { return; }
    $scope.count--;
    decremented = true;
  };
});

如果您希望用户能够重复执行此操作,那么......

angular.module('myApp', [])
.controller('CounterController', function($scope) {
   $scope.count = 15;
   var max = $scope.count + 1;
   var min = $scope.count - 1;

  $scope.increment = function() {
    if ($scope.count >= max) { return; }
    $scope.count++;
  };
  $scope.decrement = function() {
    if ($scope.count <= min) { return; }
    $scope.count--;
  };
});

JS小提琴 - http://jsfiddle.net/HB7LU/8673/

答案 3 :(得分:0)

以下是一个示例工作代码,并满足以下要求: 1)将计数器增加和减少一个 2)不使用连续迭代 3)不使用ng-init 4)适用于$ scope.count = 15

(Rasalom和smallatom已经提供的回复有所帮助,链接也是如此:http://www.w3schools.com/angular/angular_events.asp

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
    <button ng-click="count = count+1">
        Increment
    </button>
    count: {{ count }}

    <button ng-click="count = count-1">
        Decrement
    </button>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.count = 15;
});
</script> 

</body>
</html>