简体   繁体   中英

TypeError: Cannot read property 'name' of undefined in angularJS

I want to display a error message when some one forget to enter the group name. So i have created a group.name model for the input tag. Condition is checked when createGroup function is called(on submitting the form). But it is giving " TypeError: Cannot read property 'name' of undefined " while reading name property.

          <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>

Controller

 $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;
         }
  }

use angular.isDefined(); to check whether its defined or not in the scope here is the DOC

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

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