Synchronize input with Angular ngModel
by Tarek Faham
HTML
<div ng-app=app1 ng-controller="FormCtrl">
<form ng-submit="submit()">
name:<input type=text ng-model="user.name">
<br>
password: <input type=password ng-model="user.password" force-model-update>
<br>
<input type=submit value="Submit">
</form>
<hr>
<pre>debug: {{user}}</pre>
<hr>
<p>
This demo shows one possible way to walk around the problem
caused by some browsers (like FireFox) that some fields does
not fire DOM update notification events on autocomplete.
Steps to reproduce:
</p>
<ol>
<li>enter some name and password,</li>
<li>see the debug changes correctly,</li>
<li>submit,</li>
<li>let firefox remember username/password,</li>
<li>reload page,</li>
<li>click on name input field and pick remembered user,</li>
<li>NOTICE: debug shows user, BUT not the password,</li>
<li>click submit and watch debug updating the missing field.</li>
</ol>
</div>
CSS
ol {
list-style: decimal;
padding-left: 40px;
}
JavaScript
angular.module('app1', []) //
.controller('FormCtrl', function($scope) {
$scope.user = {};
$scope.submit = function() {
console.log('event:force-model-update is about to be broadcasted');
console.log($scope.user);
$scope.$broadcast('event:force-model-update');
console.log('event:force-model-update was broadcasted');
console.log($scope.user);
}
}).directive('forceModelUpdate', function($compile) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
scope.$on('event:force-model-update', function() {
ctrl.$setViewValue(element.val());
});
}
}
});