On my registration form, I have firstname , lastname , and displayname fields. When the firstname is updated, I want that value to reflect in the displayname field (should that field not already have a value).
I have set the update to occur on blur, and when I inspect the element directly for displayname , I see the value attribute set to the firstname value. However, that doesn't appear to reflect on screen or in the model. I am sure it's because that field is going off of user.displayname
(which is initially 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/
What am I missing or doing wrong? Thanks.
EDIT
One solution I came up with was $watch
ing for a change on the firstname
field, and then setting the displayname
accordingly if the value doesn't already exist. However, I do not believe this to be the "solution" as I am sure there's a more efficient way of doing this.
<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>
remove ng-model
directive in input
display
<input type="text" placeholder="Display" value="{{user.firstname}}"/>
here is the Fiddle
if you are using ng-model
angular try to find the value of that model name, so textbox is not updating because there is no value for that model name user.displayname
.
another alternative coud be by triggering and watch mouse event on first input.
<input type="text" ng-model="user.firstname" ng-mouseleave="checkDisplayName($event)" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.