I am attempting to set default values for certain model properties by using $watches. I cannot utilize the typical two-way binding because I want the model properties to start off as empty. Although the $watches are successfully setting the properties, the associated HTML is not being updated.
<!doctype html>
<body ng-app="TestApp" ng-controller="TestCtrl">
<div><input ng-model="form.firstname" placeholder="enter your first name"/></div>
<div><input ng-model="form.lastname" placeholder="enter your last name"/></div>
<p>{{user.firstname}}</p>
<p>{{user.lastname}}</p>
</body>
angular.module('TestApp', [])
.controller('TestCtrl', ['$scope', function($scope) {
$scope.user = new User({
firstname: 'Bruce',
lastname: 'Wayne'
});
function User(defaults) {
angular.extend(this, defaults);
$scope.form = {};
angular.forEach(this, function(value, key) {
$scope.form[key] = '';
$scope.$watch(function() {
return $scope.form[key];
}, function (val) {
this[key] = val || defaults[key];
console.log(val)
console.log(defaults[key])
console.log(this[key])
});
});
}
}]);
Check out a fiddle here - my objective is for any input value to be displayed in the text, and if the value is removed, the default text appears again. The watch callback seems to be functioning correctly based on console logs. I did attempt to use $apply to update but encountered a $digest in progress error.
I am fairly new to Angular, so there's a possibility I am going about this the wrong way!