最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS Cannot read property of undefined - Stack Overflow

programmeradmin1浏览0评论

I am trying to get a date value. Whenever the the checkbox is unchecked and the date picker is invisible I am getting the error that : 'Cannot read property 'NTLI' of undefined'. if the check box is checked and the date picker is visible everything works fine

<md-checkbox ng-model="user.NTLI" layout="row" ng-disabled="userForm.$invalid">
  NTLI
</md-checkbox>
<div ng-show="user.NTLI">
<fieldset class="standard">
    <legend>NTLI</legend>
    <md-input-container>
        <label>Efective date</label>
        <md-datepicker ng-model="user.efectiveDateNTLI"></md-datepicker>
    </md-input-container>
</fieldset>
</div>
var efDate = '';
if ($scope.user.NTLI != undefined) 
{
    efDate = $scope.user.efectiveDateNTLI
}

I am trying to get a date value. Whenever the the checkbox is unchecked and the date picker is invisible I am getting the error that : 'Cannot read property 'NTLI' of undefined'. if the check box is checked and the date picker is visible everything works fine

<md-checkbox ng-model="user.NTLI" layout="row" ng-disabled="userForm.$invalid">
  NTLI
</md-checkbox>
<div ng-show="user.NTLI">
<fieldset class="standard">
    <legend>NTLI</legend>
    <md-input-container>
        <label>Efective date</label>
        <md-datepicker ng-model="user.efectiveDateNTLI"></md-datepicker>
    </md-input-container>
</fieldset>
</div>
var efDate = '';
if ($scope.user.NTLI != undefined) 
{
    efDate = $scope.user.efectiveDateNTLI
}
Share Improve this question edited Jan 3, 2017 at 11:39 Nope 22.3k8 gold badges49 silver badges73 bronze badges asked Jan 3, 2017 at 11:30 user7199461user7199461 3
  • In your controller, make it so user.NTLI = false;, you get this error because it doesn't exist. – Tom Johnson Commented Jan 3, 2017 at 11:34
  • Do you have anywhere in your app which is bound to user itself? – Yaser Commented Jan 3, 2017 at 11:34
  • One suggestion(little off topic) : leave the habit of writing { on next line. It should be on same line. – Saurabh Bayani Commented Jan 3, 2017 at 11:43
Add a ment  | 

4 Answers 4

Reset to default 3

You need to have user defined,

$scope.user ={};
if ($scope.user.NTLI != undefined) 
{
    efDate = $scope.user.efectiveDateNTLI
}

What is initial value if your user object? You need it initialized first to be accessible from $scope.

$scope.user = {};

Assign user = {} on ng-init

like

<div ng-init="user = {}"> 
...
..//code
...
</div>

But other answers are also correct.

As user is not available it shows undefined when reading property of it. Just add following:

$scope.user = {};

in your controller.

发布评论

评论列表(0)

  1. 暂无评论