In the registration form, there are fields for firstname, lastname, and displayname. When the firstname is updated, I want that change to be reflected in the displayname field if it's currently empty.
I've set the update to happen on blur, and after inspecting the element directly for displayname, I noticed the value attribute is being set to the firstname value. However, this change doesn't seem to appear on screen or in the model. The issue seems to be because the field is referencing user.displayname
(which starts off as empty).
<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/
Any suggestions or insights on what might be causing this? Thank you.
EDIT
One workaround I came up with was using $watch
to monitor changes in the firstname
field and updating the displayname
accordingly only if it's empty. However, I believe there must be a better and more efficient solution to address this issue.
<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>