【问题标题】:TypeError: Cannot read property 'name' of undefined in angularJSTypeError:无法读取 angularJS 中未定义的属性“名称”
【发布时间】:2015-04-10 08:37:27
【问题描述】:

当有人忘记输入组名时,我想显示一条错误消息。所以我为输入标签创建了一个 group.name 模型。调用 createGroup 函数时检查条件(提交表单时)。但它给 “TypeError: Cannot read property 'name' of undefined”在读取名称属性时。

          <form name="serverGroup" role="form" ng-model="group" ng-submit="createGroup(group)">
                <div class="form-group createGrpField">
                    <label for="groupname" class="nameField">Name</label>
                    <input id="nameField" type="text" ng-model="group.name" class="form-control" placeholder="Enter group name" />
                </div>

                <div class="createServerPadding">
                    <button id="saveBtn" class="btn btn-default btn-primary" type="submit">Save</button>
                    <button class="btn btn-default" type="cancel">Cancel</button>
                </div>
            </form>

控制器

 $scope.createGroup = function(group) {
        selectedRows = $scope.gridApi.selection.getSelectedRows();

        $scope.emptyName = false
        $scope.selectServer = false;

        if (!group.name || !group) {
            console.log("group", group);
            $scope.emptyName = true;
            $scope.selectServer = false;
         }
  }

【问题讨论】:

  • 每次都会出现吗?您是否尝试填写表格并提交?
  • 为什么ng-model="group" 在表单上?
  • if 块中的条件顺序错误。首先检查group
  • 你应该改变 if (!group || !group.name) { 其他方式没有意义的顺序。

标签: javascript angularjs


【解决方案1】:

使用angular.isDefined();检查其在此处定义的范围是否为DOC

if ( angular.isDefined(group) && group.hasOwnProperty('name') ) {
    console.log("group", group);
    $scope.emptyName = true;
    $scope.selectServer = false;
 }

【讨论】:

    猜你喜欢
    • 2021-11-13
    • 2022-01-14
    • 2022-06-22
    • 2015-10-16
    • 2021-12-28
    • 2021-08-16
    • 2020-10-11
    • 2019-09-06
    • 1970-01-01
    相关资源
    最近更新 更多