2

I'm trying to configure my app to show an alert when the user tries to submit a form with an empty input box, but can't get it working even though I've a confirmation popup elsewhere in the same application.

Any ideas why this code might not be working?

Codepen: http://codepen.io/anon/pen/VpjgJJ.

JS:

$scope.addTask = function() {
        if ($scope.taskName.length == "") {
            $scope.showAlert = function(ev) {
                $mdDialog.show(
                    $mdDialog.alert()
                        .parent(angular.element(document.querySelector('#popupContainer')))
                        .clickOutsideToClose(true)
                        .title('Error')
                        .textContent('You must enter a task name')
                        .ok('Close')
                        .targetEvent(ev)
                )
            }
        }

HTML:

<form class="md-padding">

  <div layout-gt-sm="row">

  <md-input-container class="md-block" flex-gt-sm>

    <label>Add New Task</label>

    <input type="text" ng-model="taskName" size="50">

  </md-input-container>

</div>

<md-button ng-click="addTask()" class="md-raised md-primary">Add</span></md-button>

2
  • Why not use required attribute? Commented Mar 5, 2017 at 18:00
  • I'm trying to configure it to use the alert message, which wouldn't automatically appear Commented Mar 5, 2017 at 18:06

2 Answers 2

1

I updated your demo and made it work. Please check this working demo. You had a couple of problems in your code: e.g. try to load unkown ressources, use of undefined variables and wrong operations like $scope.taskName.length == "". Finaly your code works:

if (angular.isUndefined($scope.taskName) || $scope.taskName.length === 0) {

    var alert =  $mdDialog.alert()
        .parent(angular.element(document.querySelector('#popupContainer')))
        .clickOutsideToClose(true)
        .title('Error')
        .textContent('You must enter a task name')
        .ok('Close');

    $mdDialog.show( alert )
        .finally(function() {
            alert = undefined;
        });
}
Sign up to request clarification or add additional context in comments.

Comments

0

The reason why your code is not working is because in this line:

$scope.taskName.length == ""

taskName variable in your scope is never initialized (even with an empty value) if that field was not modified by user.

Some recommendations:

  1. Create a task object in your $scope:

$scope.task = {}

  1. Change your input declaration to <input type="text" ng-model="task.name" size="50">
  2. $scope.taskName.length == "" looks weird, use $scope.taskName.length === 0

Comments

Your Answer

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