Phoenix Phoenix - 29 days ago 5
Javascript Question

Clear value inside a text box in AngularJS without manipulating data in ng-model

I have a form for password updation.
HTML :

<div class="profile-fields">

<p>Please provide your profile details</p>

<div class="field">
<label for="username">User Name</label>
<input type="text" name="username" value="" placeholder="UserName" ng-model="profile.name" ng-disabled="true" />
</div>

<div class="field">
<label for="password">Password:</label>
<input type="password" name="password" placeholder="Password" ng-model="profile.password" value="" validator="required" required-error-message="Password is required" valid-method="watch" />
</div>
<div class="field">
<label for="password">Retype Password:</label>
<input type="password" name="password1" value="" placeholder="Password" ng-model="password1" validator="required" required-error-message="Password is required" valid-method="watch" />
</div>
</div>


The new password is sent from the first password box using
ng-model="profile.password"


Controller :

myApp.controller('profileController', ['$scope', 'userResolved', 'userServices', '$location', function ($scope, userResolved, userServices, $location) {

$scope.oldPassword = userResolved.data.password;
$scope.profile = userResolved.data;
$scope.cancelProfile = function () {


$location.path("/dashboard");


}
$scope.updateProfile = function () {

if ($scope.profileForm.$valid && $scope.profile.password == $scope.password1) {
if ($scope.profile.password != $scope.oldPassword) {
userServices.saveProfile($scope.profile).then(function (result) {
if (!result.error) {
alert("Profile updated!!! Please login again with new password.");
$location.path("/logout");
}
})
.catch(function (data) {
$scope.error = data.data;
});
}
else {
$scope.error = "Password cannot be same as before!!"

}

}
else {
$scope.error = "Passwords mismatch!!"
}
};
}]);


The problem is that on page load the model is displaying the current password in the first password text box. User will have to manually clear the current password from the first textbox to enter the new one. I can't just clear the
profile.password
because I am using it for validation. Is there anyway we can clear the value inside the element on page load in a way that we are not manipulating ng-model?

The text box should not display the current password on page load. How can I achieve this?

Answer

Create a new var and assign that var the password, and then clear the model variable.

var myPassword = profile.password;

profile.password = "";
Comments