How to reset incresed Value to it's initial value in AngularJs

痴心易碎 提交于 2019-12-12 05:08:23

问题


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


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

{{count}}   //Here Value will increase

And count value changed...

Q1.My question is How do i reset that value to 23 and display ? OR store that value in a variable.

Q2. Suppose count value increased from 23 to 29 by clicking. And how to get that value 29.


回答1:


You can store the initial value in a variable and then reuse it. Here's the 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);
    };
    });



回答2:


Q1.My question is How do i reset that value to 23 and display ? OR store that value in a variable.

$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. Suppose count value increased from 23 to 29 by clicking. And how to get that value 29.

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



回答3:


You should hold a variable in your controller (constant is more appropriate) with which you will reset your count whenever you want.

Controller

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

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

Template

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

{{count}}

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


来源:https://stackoverflow.com/questions/37831737/how-to-reset-incresed-value-to-its-initial-value-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!