gpt4 book ai didi

javascript - 使用单一模型编辑多个变量

转载 作者:搜寻专家 更新时间:2023-10-31 23:02:06 27 4
gpt4 key购买 nike

有没有办法只使用一个模型来编辑三个不同的变量?因为在当前的方法中,看起来只是变量值被复制到“editedVar”。

Fiddle of the code below

<div ng-controller="MyCtrl">
A: {{A}}<br/> B: {{B}} <br/> C: {{C}}<br/>
<input ng-model="editedVar"/>
<br/>
<button ng-click="switchToA()">Switch to A</button>
<button ng-click="switchToB()">Switch to B</button>
<button ng-click="switchToC()">Switch to C</button>
</div>




var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
$scope.A = 1;
$scope.B = 2;
$scope.C = 3;

$scope.switchToA = function()
{
$scope.editedVar = $scope.A;
};

$scope.switchToB = function()
{
$scope.editedVar = $scope.B;
};

$scope.switchToC = function()
{
$scope.editedVar = $scope.C;
};
}

最佳答案

您可以通过多种方式实现,这里是一种简单且更干货的方式。

查看(保持简单,只有一个函数可以更改当前编辑的变量):-

<input ng-model="editedVar[editing]" />
<br />
<button ng-click="switchTo('A')">Switch to A</button>
<button ng-click="switchTo('B')">Switch to B</button>
<button ng-click="switchTo('C')">Switch to C</button>

Controller :-

function MyCtrl($scope) {
/*Keep the values in an object with respective property name*/
$scope.editedVar = {
A: 1,
B: 2,
C: 3
}

/*Set the default edit property*/
$scope.editing = 'A';

/*Sets the currently edited property based on what is being passed in*/
$scope.switchTo = function (prop) {
$scope.editing = prop;
};

}

Fiddle

您也可以这样做,但只能在不使用对象的情况下使用更多维护代码。

查看:-

<input ng-model="editedVar" ng-change="valueChange()"/>
<br/>
<button ng-click="switchTo('A')">Switch to A</button>
<button ng-click="switchTo('B')">Switch to B</button>
<button ng-click="switchTo('C')">Switch to C</button>

Controller :-

function MyCtrl($scope) {

$scope.A = 1;
$scope.B = 2;
$scope.C = 3;

var editing;
/*Change event to keep the value in sync*/
$scope.valueChange = function(){
$scope[editing] = $scope.editedVar;
}
/*Just one function*/
$scope.switchTo = function (prop) {
$scope.editedVar = $scope[editing = prop];
};

}

Fiddle

关于javascript - 使用单一模型编辑多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27772920/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com