![](/img/trans.png)
[英]Can Angular do two way data binding backwards between two input fields?
[英]One way data binding on 2 input fields
在我的注冊表上,我有firstname , lastname和displayname字段。 更新姓氏時 ,我希望該值反映在displayname字段中(如果該字段尚未有值)。
我將更新設置為在模糊時發生,當我直接檢查元素的displayname時 ,我看到value屬性設置為firstname值。 但是,這似乎並沒有反映在屏幕上或模型中。 我確定是因為該字段不屬於user.displayname
(最初為空)。
<div ng-app="myApp">
<form ng-controller="RegisterCtrl">
<input type="text" ng-model="user.firstname" placeholder="Firstname" ng-model-options="{updateOn: 'blur'}"/>
<input type="text" ng-model="user.lastname" placeholder="Lastname" />
<input type="text" ng-model="user.displayname" placeholder="Display" value="{{user.firstname}}"/>
</form>
</div>
<script>
var myApp = angular.module("myApp", []);
myApp.controller("RegisterCtrl", ["$scope" ,function ($scope) {
$scope.user = {};
}]);
</script>
JSFiddle: http : //jsfiddle.net/mbqs7xcj/
我想念什么或做錯什么? 謝謝。
編輯
我想出的一個解決方案是$watch
firstname
字段的更改,然后如果該值尚不存在,則相應地設置displayname
。 但是,我不認為這是“解決方案”,因為我確信有更有效的方法可以做到這一點。
<script>
var myApp = angular.module("myApp", []);
myApp.controller("RegisterCtrl", ["$scope", function ($scope) {
$scope.user = {
firstname: "",
lastname: "",
displayname: "",
email: "",
password: ""
};
// Set the firstname as the display name if it's empty
$scope.$watch("user.firstname", function () {
if ($scope.user.displayname.length === 0) {
$scope.user.displayname = $scope.user.firstname;
}
});
}]);
</script>
在input
顯示中刪除ng-model
指令
<input type="text" placeholder="Display" value="{{user.firstname}}"/>
這是小提琴
如果您使用的是ng-model
angular,請嘗試查找該模型名稱的值,因此不會更新文本框,因為該模型名稱user.displayname
沒有值。
另一個替代方法是在第一個輸入上觸發並監視鼠標事件。
<input type="text" ng-model="user.firstname" ng-mouseleave="checkDisplayName($event)" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.