0

how to handle empty input on angular?

I want validate on back end not on front end. But when i submit it return me error if i let it blank on icon input

 TypeError: Cannot read property 'icon' of undefined

Here is my form:

 <div class="form-group">
                    <div class="form-material form-material-danger">
                        <input class="form-control" type="text" id="name" ng-model="menu.name" placeholder="Menu Name.." empty-to-null>
                        <label for="name">Name</label>
                    </div>
                </div>
                <div class="form-group">
                    <div class="form-material form-material-danger">
                        <input class="form-control" type="text" id="icon" ng-model="menu.icon" placeholder="Menu Icon.." >
                        <label for="icon">Icon</label>
                    </div>
                </div>

Here is my code:

 var data = {
            icon: $scope.menu.icon,
            name: $scope.menu.name
        };

        AdminMenu.save(data, function (response) {
            console.log(response);
            $scope.menu = null;
            ResultService(response);
            $scope.dtInstance.reloadData();
        }, function (response) {
            ResultService(response.data);
        })
            .$promise.finally(function () {
                $scope.button_text = "Store";
                $scope.loading = false;
            });
3
  • this example isn't complete. where is the menu object created, and where is the data object used? Commented Oct 5, 2015 at 9:18
  • Hi. Scope menu is from the view. i just take it from the ng-model. data object is get from input at front end. @Claies Commented Oct 5, 2015 at 9:21
  • ok, thanks for letting me know, but this is still not a code sample that can be tested to reproduce your issue. Commented Oct 5, 2015 at 9:25

1 Answer 1

1
$scope.menu = null

When you set menu to null, angular can't find menu.icon anymore. You should do $scope.menu = {} if you want to "reset" it.

And, of course, don't forget to initialize $scope.menu before using it.

Sign up to request clarification or add additional context in comments.

4 Comments

i don't want to reset it. I just want if i press submit, it submit to backend and return error from backend. Right now if i submit, it return me undefined
So what is the purpose of $scope.menu = null ?
is after submit. it reset the form. right now the error is at var data = {icon: $scope.menu.icon}
becuae $scope.menu is not defined before accessing it...define $scope.menu = {} before data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.