I am looking to create a reusable controller that can be used by multiple views. This controller will essentially serve as a template.
The issue I'm facing is with setting up simple validation. The problem lies in the fact that the properties set in ng-model
cannot be read unless changes are made to a field, which then adds that property to the object.
I am reluctant to include
ng-init="object.fieldName = null"
on every field in my view as I do not consider it to be good practice. While attempting to use $watch
, I found that the object remained empty {}.
Below is the Controller code snippet:
angular.module('practiceApp')
.controller("CreateModalController", function($scope, items, defaultService) {
function initialize() {
$scope.object = {}; // <---- this should contain the ng-model object properties
$scope.defaultService = defaultService;
$scope.modalTitle = items.modalTitle;
$scope.$watch('object', function(newValue, oldValue) {
console.log(newValue);
}, true);
}
initialize();
});
Here's what my view looks like:
<form name = "objectForm"
role = "form">
<input type="text"
ng-model="object.firstName"
class="form-control"
placeholder="First Name"
ng-class="{'error-textfield': defaultService.isNotValid(object.firstName)}"
required>
<input type="text"
ng-model="object.lastName"
class="form-control"
placeholder="Last Name"
ng-class="{'error-textfield': defaultService.isNotValid(object.lastName)}"
required>
</form>
Current output => object: {}
Desired output =>
object: {firstname: undefined, lastName: undefined}