angularjs仅在事件上绑定数据

时间:2015-03-05 07:17:46

标签: javascript angularjs

我有一个表单,我只想在用户点击按钮时绑定它的值 当用户选择重置/取消时,我想回到原始模型数据。 怎么做到呢? http://jsfiddle.net/1y9ft817/ 感谢

<div ng-controller="MyCont" ng-app>
<form>
    <input type="number" min="0" max="50" value="{{value}}" ng-model="value" />{{value}}
    <br />
    <input type="submit" value="bind the data" />
    <input type="reset" value="reset back to 15" />
</form>

function MyCont($scope) {
    $scope.value = 15;
};

4 个答案:

答案 0 :(得分:0)

function MyCont($scope) {
    $scope.value = 15;
    $scope.tmpValue = $scope.value;
};


<div ng-controller="MyCont" ng-app>
<form>
    <input type="number" min="0" max="50" ng-model="tmpValue" />{{tmpValue}}
    <br />
    <btn ng-click="value = tmpValue">Submit</btn>
    <btn ng-click="tmpValue = value">Reset</btn>
</form>

答案 1 :(得分:0)

您需要模型来跟踪旧值和新值

<div ng-controller="MyCont" ng-app>
    <form>
        <input type="number" min="0" max="50" value="{{value.newVal}}" ng-model="value.newVal" />{{value.newVal}}
        <br />
        <br />
        <input type="submit" value="bind the data" ng-click="bindVal()" />
        <input type="reset" ng-click="resetVal()"value="reset back to 15" />
    </form>
</div>

function MyCont($scope) {
    $scope.value = {
        oldVal:15,
        newVal:15
    }
    $scope.bindVal=function(){
    $scope.value.oldVal=$scope.value.newVal;

    }
    $scope.resetVal=function(){
    $scope.value.newVal=$scope.value.oldVal;
    }
};

Fiddle: -

答案 2 :(得分:0)

取消了Squiroid,但修复了重置。

function MyCont($scope) {
$scope.value = {
    origVal:15,
    oldVal:15,
    newVal:15
}
$scope.bindVal=function(){
$scope.value.oldVal=$scope.value.newVal;

}
$scope.resetVal=function(){
$scope.value.oldVal=$scope.value.origVal;
}

http://jsfiddle.net/gzuhtx9c/

答案 3 :(得分:0)

如果我正确地满足了您的需求(您希望通过单击btns添加/删除输入值与显示值之间的连接),您可以像这样实现它:

<div ng-controller="MyCont" ng-app>
<form>  
    <input type="number" min="0" max="50" value="{{value}}" data-ng-model="value"/> 
    {{displayValue}}
    <br />
    <br />
    <input type="submit" value="bind the data" data-ng-click="bindVal()" />
    <input type="reset" value="reset back to 15" data-ng-click="resetVal()" />
</form>

function MyCont($scope) {
var isValueReallyBinded = true,
    initialValue = 15;
$scope.value = initialValue;

$scope.$watch('value', function (newVal, oldVal) {
    if(isValueReallyBinded) {
        $scope.displayValue = $scope.value;
    }
    else {
        $scope.displayValue = initialValue;
    }
});

$scope.bindVal = function () {
    isValueReallyBinded = true;
    $scope.displayValue = $scope.value;
};
$scope.resetVal = function () {
    isValueReallyBinded = false;
    $scope.displayValue = initialValue;
};
};