gpt4 book ai didi

AngularJS - 类型错误 : Cannot read property X of undefined

转载 作者:行者123 更新时间:2023-12-01 13:38:56 27 4
gpt4 key购买 nike

我在表单中有 2 个字段时遇到问题。它们都在页面加载时返回为 undefined 并出现以下错误。 (注意我删除了 url 和唯一路径名,但留下了核心错误段。)

类型错误:无法读取未定义的属性“card_number”

类型错误:无法读取未定义的属性“ssn”

    at r.$scope.isSsnRequired (/js/ng-app/components/controller.js:67:23)
at Object.fn [as get] (eval at <anonymous> (/js/angular.min.js:216:110), <anonymous>:4:230)
at r.$digest (/js/angular.min.js:131:156)
at r.$apply (/js/angular.min.js:134:236)
at /js/angular.min.js:20:59
at Object.e [as invoke] (/js/angular.min.js:39:431)
at c (/js/angular.min.js:19:482)
at zc (/js/angular.min.js:20:274)
at ce (/js/angular.min.js:19:83)
at HTMLDocument.<anonymous> (/js/angular.min.js:297:355)

错误来自 Controller :
$scope.isCardNumberRequired = function() 
{
if (!(angular.isUndefined($scope.formData.ssn)))
{
if ($scope.formData.ssn.length > 0)
{
return false;
}
}

return true;
};

$scope.isSsnRequired = function()
{
if (!(angular.isUndefined($scope.formData.card_number)))
{
if ($scope.formData.card_number.length > 0)
{
return false;
}
}

return true;
};

它们正在以具有以下代码的形式创建。
    <form id="mainFormId" method="post" class="form" role="form" name="mainForm" novalidate>
<div class="row form-group">
<div class="control-label col-xs-4">Card #</div>
<div class="col-xs-8">
<input
type="text"
class="form-control"
name="card_number"
ng-model="formData.card_number"
ng-class="{'admin_error_field_bold_border': mainForm.card_number.$invalid && mainForm.$submitted}"
ng-required="isCardNumberRequired()"
ng-maxlength="16"
ng-pattern="/^\d{16}$/"
/>
<div ng-show="mainForm.$submitted">
<span class="text-danger" ng-show="mainForm.card_number.$error.maxlength">Allowed maximum length is 16 digits.<br /></span>
<span class="text-danger" ng-show="mainForm.card_number.$error.pattern">Card # is invalid.<br /></span>
</div>
</div>
</div>

<div class="row form-group">
<div class="control-label col-xs-4">SSN</div>
<div class="col-xs-8">
<input
type="text"
class="form-control"
name="ssn"
ng-model="formData.ssn"
ng-class="{'admin_error_field_bold_border': mainForm.ssn.$invalid && mainForm.$submitted}"
ng-required="isSsnRequired()"
ssn
/>
<div ng-show="mainForm.$submitted">
<span class="text-danger" ng-show="mainForm.ssn.$error.ssn">Invalid SSN.<br /></span>
</div>
</div>
</div>
</form>

感谢您抽出时间来查看。

最佳答案

在您的 Controller 中,您需要定义 formData在开始时,如果您希望该错误在页面加载时消失:

$scope.formData = {};

然而,当页面加载时,你调用函数 isCardNumberRequiredisSsnRequired formData不会未定义,因为它已经由 AngularJS 机制创建。

关于AngularJS - 类型错误 : Cannot read property X of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41981696/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com