I've been developing a custom input wrapper that includes error text handling, among other functionalities. However, I'm facing an issue where I can't reset the model values. Upon inspecting the scopes, I noticed that the outer scopes get updated on reset, but the inner scope of the directive does not update, and I'm uncertain about the cause.
Changing the ng-model watch in the directive from `scope.$watch(ngModel, function() {` to `scope.$watch('ngModel', function() {` enables the reset to work; however, the reset fails when the viewValue is invalid. Ideally, the reset should also work in this scenario.
Could I be making a grave mistake somewhere? The code below demonstrates the issue:
var app = angular.module('app', []);
app.directive('myInput', function() {
return {
restrict: "E",
require: "ngModel",
template: $('#myInput').html(),
scope: {
"ngModel": "=",
"name": "@",
"type": "@",
"label": "@",
"errorLabel": "@",
"placeholder": "@"
},
link: function(scope, element, attributes, ngModel) {
scope.$watch('ngModel', function() {
scope.value = scope.ngModel;
console.log('got value: ' + scope.value);
});
scope.$watch('value', function() {
if(scope.value) {
ngModel.$setViewValue(scope.value);
}
});
}
};
});
app.controller('user', ['$scope', function($scope) {
$scope.currentUser = {
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="15657067667a7b55667c61703b767a78">[email protected]</a>"
};
$scope.resetUser = function() {
console.log('resetting user');
console.log($scope.user);
$scope.user = angular.copy($scope.currentUser);
console.log($scope.user);
};
$scope.submitUser = function(user) {
console.log('submitting user');
console.log(user);
};
$scope.resetUser();
}]);
.error {
color: red;
}
.my-input {
border: 5px solid transparent;
}
.ng-invalid.my-input {
border: 5px solid red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script type="text/html" id="myInput">
<ng-form name="thisForm">
<label
ng-class="{error: thisForm.$invalid}"
for="{{name}}"
ng-bind="thisForm.$valid ? label : errorLabel"></label></br>
<input
class="my-input"
name="{{name}}"
type="{{type}}"
placeholder="{{placeholder}}"
ng-model="value"></input>
</ng-form>
</script>
</head>
<body ng-app="app">
<div ng-controller="user">
<ng-form name="userForm">
<my-input
type="email"
ng-model="user.email"
error-label="Enter a valid Email"
label="Email"
placeholder="Enter an Email"
name="Email"></my-input>
</br>
<button ng-click="resetUser()">Reset</button>
<button ng-click="submitUser(user)" ng-disabled="userForm.$invalid">Submit</button>
</ng-form>
</div>
</body>
</html>