简体   繁体   中英

AngularJS - Controller cannot read ng-model object property

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}

The output will initially be object: {} because you haven't initially declared $scope.object to have any properties on it. It will only have the firstName or lastName property visible when you enter text into the <input> to trigger ng-model into updating $scope.object .

If you want to have it initially show has the desired output you've provided, declare your object initially in the controller to have undefined properties:

$scope.object = {
  firstName: undefined,
  lastName: undefined
};

On a side note, you shouldn't need to self-initialize via your initialize() function in your controller if you've already declared the controller in your routing.

Also, if you're using AngularJS 1.5+ components, you can use $onInit() .

see working code:

 <!DOCTYPE html> <html> <body> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <script> var app = angular.module('practiceApp', []); app.controller("CreateModalController", function($scope) { function initialize() { $scope.object = { firstName: null, lastName: null }; // <---- 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(); }); </script> <div ng-app="practiceApp" ng-controller="CreateModalController"> <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> </div> </body> </html> 

Even if you don't want to initialize values you will see values of firstName and lastName after you start typing. While user don't enter anything into input fields there was no values in 'object' so there is nothing to show.

Any questions?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM