Neha Gupta
Neha Gupta

Reputation: 1067

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

Upvotes: 0

Views: 3608

Answers (1)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

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

Upvotes: 1

Related Questions