简体   繁体   中英

AngularJS - Attach Alert Popup to Empty Input

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>

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

I updated your demo and made it work. Please check this working demo . You had a couple of problems in your code: eg 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;
        });
}

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