I want to make a controller that can be reused by other views. (This controller will serve as a template)
The problem is that I can't make a simple validation because it can't read the properties that is set in ng-model unless I made changes on a field, then that property will be added to that object.
I don't want to put ng-init="object.fieldName = null" to every field in my view because I believe that it's not a good practice. I tried using $watch but the object is still equals to {}
Here's my Controller:
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 my view:
<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}