如何将增加的值重置为AngularJs中的初始值

时间:2016-06-15 09:42:04

标签: javascript angularjs angularjs-ng-click

$scope.count = 23;  // this is the initial value


<button ng-click = "count = count + 1"> Increase</button>

{{count}}   //Here Value will increase

计数值改变了......

Q1.我的问题是如何将该值重置为23并显示?或将该值存储在变量中。

Q2。假设通过单击将计数值从23增加到29。以及如何获得这个价值29。

3 个答案:

答案 0 :(得分:1)

您可以将初始值存储在变量中,然后重复使用它。这是fiddle

<强> HTML:

<div ng-app="app" ng-controller="MainController">
{{initialValue}}
<button ng-click="increase()">Increase</button>
<button ng-click="reset()">Reset</button>
</div>

<强> JS:

    var app=angular.module('app',[]);
    app.controller('MainController',function($scope){
    var initialValue=20;
    $scope.initialValue=initialValue;
    $scope.reset=function(){
    $scope.initialValue=initialValue;
    };
    $scope.increase=function(){
    $scope.initialValue+=1;
    console.log('Increase value', $scope.initialValue);
    };
    });

答案 1 :(得分:0)

您应该在控制器中保存一个变量(常数更合适),您可以随时根据需要重置count

<强> 控制器

$scope.initialValue = 23;
$scope.count = $scope.initialValue;

function resetCounter() {
    $scope.count = $scope.initialValue;
}

<强> 模板

<button ng-click = "count = count + 1"> Increase </button>

{{count}}

<button ng-click = "resetCounter()"> Reset </button>

答案 2 :(得分:0)

Q1.我的问题是如何将该值重置为23并显示?或者将该值存储在变量中。

$scope.count = 23;  // this is the initial value
<button ng-click = "count = count + 1"> Increase</button>
<button ng-click = "count = 23"> Reset</button>
{{count}}   //Here Value will increase

Q2。假设通过单击将计数值从23增加到29。以及如何获得这个价值29。

$scope.get = 0;
<button ng-click = "get = count"> Get</button>
{{get}}