尝试将第一个输入字段值自动填充到第二个输入字段值,但是如果第二个输入字段为现有值,那么我想将第一个输入字段值追加/连接到第二个。
逻辑:
if ( second ){
second = first + second;
}else{
second = first;
}
HTML:
<input type='text' ng-model='owner' required class="form-control">
<input type='text' ng-model='member' required class="form-control">
代码:
app.controller("Controller", ['$scope', function($scope){
$scope.$watch(function () {
return $scope.owner;
},
function (newValue, oldValue) {
if ( $scope.member ){
$scope.member = $scope.owner + ',' + $scope.member;
}else{
$scope.member = newValue;
}
}, true);
}]);
更新(问题):
当我在所有者字段中键入Jake
时,它会循环显示字母并在成员字段中打印为Jake,Jak,Ja,J
。如果我在成员字段中预先存在值Adam
,则在所有者归档中输入Tom
后,它将在成员字段中创建Tom,To,T,Adam
。请检查plunker进行演示。
答案 0 :(得分:1)
Mad-D考虑改变你的方法,因为它很容易根据ng-model的工作方式产生循环依赖。
您已经可以访问这两个值,并且可以通过其他方式显示它们。此外,您的控制器看起来更干净,并充当真正的视图模型(vm):
<强> Plunker 强>
app.controller("Controller", function(){
var myCtrl = this;
myCtrl.owner = "";
myCtrl.member = "";
});
答案 1 :(得分:0)
我创建了plnkr 。并在下面给出。检查一下它是否正确。
var app = angular.module('form-example1', []);
app.controller("Controller", ['$scope', function($scope){
$scope.permaMember = $scope.member?$scope.member:'';
$scope.editSecond = function(member){
$scope.permaMember = member?member:'';
}
$scope.editFirst = function(owner){
if(owner){
$scope.member = $scope.permaMember + owner
}
else{
$scope.member = $scope.permaMember
}
}
}]);
&#13;
<!doctype html>
<html ng-app="form-example1">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div ng-controller="Controller">
<form name="testform">
<div class='form-group'>
<label>Owner</label>
<input type='text' ng-model='owner' required class="form-control" ng-change="editFirst(owner)">
</div>
<div class='form-group'>
<label>Member</label>
<input type='text' ng-model='member' required class="form-control" ng-change="editSecond(member)">
</div>
<button ng-disabled="testform.$invalid" ng-click ="submit()">SAVE</button>
</form>
</div>
</body>
</html>
&#13;
答案 2 :(得分:-1)
为什么不只有第3个只读文本框或标签显示$ scope.owner,$ scope.member?