2 个输入字段上的单向数据绑定

One way data binding on 2 input fields

本文关键字:数据绑定 输入 字段      更新时间:2023-09-26

在我的注册表上,我有名字姓氏显示名称字段。当名字更新时,我希望该值反映在显示名称字段中(如果该字段还没有值)。

我已将更新设置为在模糊时进行,当我直接检查元素的显示名称时,我看到值属性设置为名字。但是,这似乎并没有反映在屏幕或模型中。我敢肯定这是因为该字段正在脱离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>

http://jsfiddle.net/mbqs7xcj/7/

删除input显示中的ng-model指令

<input type="text"  placeholder="Display"  value="{{user.firstname}}"/>

这是小提琴

如果您使用的是ng-model角度尝试查找该模型名称的值,因此 TextBox 不会更新,因为该模型名称没有值user.displayname

另一种选择是在第一次输入时触发并观察鼠标事件。

<input type="text" ng-model="user.firstname" ng-mouseleave="checkDisplayName($event)" />

http://jsfiddle.net/darul75/mbqs7xcj/9/