Search code examples
angularjs-model

AngularJS: Why ng-model scope's variable is not shown in inspector if input field is empty?


I have an input form like this:

<form name="userForm">
    <md-input-container>
        <label>Username</label>
        <input name="username" ng-model="userLogin.username" required>
        <div ng-messages="userLogin.username.$error" ng-show="userLogin.username.$dirty">
            <div ng-message="required">This is required!</div>
        </div>
    </md-input-container>

</form>
<div layout="row" layout-align="center">
    <md-button class="md-raised md-primary md-padding button-margin" ng-click="handleLoginResult()" ng-disabled="!userForm.$valid">Login</md-button>
</div>

The problem is that until I don't write anything in the input field (= user interaction), the userLogin.username variable doesn't appear in the $scope (I'm using AngularJS' addon for Chrome dev console). Indeed if I try to print it I get erro (userLogin is not defined >> username can't be read).

Any clue?


Solution

  • Typically, in an AngularJS controller, if you do not create the property implicitly on the $scope object it will not be defined until a bound element attempts to update it. This is just the nature of how AngularJS works and the nature of dynamic Javascript. Is there a reason you need to get to the property if it isn't defined yet? From your question I am assuming that you were just prodding it with the console. If you really need to use it in a function before it is defined use the OR logical operator in Javascript represented by two pipe characters:

    $scope.userLogin || '';