добавить класс, когда ввод действителен в angularjs

У меня есть ошибка в моей форме angularjs. Я хочу изменить класс элемента, когда ввод из формы angularjs действителен, и изменить его обратно, если он недействителен.

Я получил этот код:

<li data-ng-class="{ success: userFormRegistration.email.$valid, danger: userFormRegistration.email.$invalid }" class="danger">valid email</li>

Теперь это ввод электронной почты:

<input type="email" name="email" data-ng-model="userFormRegistration.email" class="form-control ng-pristine ng-invalid ng-invalid-required ng-invalid-email" placeholder="Email" required="">

В начале добавлен класс danger, но когда я ввожу действительный адрес электронной почты, он удаляет класс, но не добавляет класс success.

Вот код angularjs:

// app.js
            // create angular app
            var FormApp = angular.module('FormApp', []); ;


            // create angular controller
            /*FormApp.controller('registrationFormController', function ($scope, $http) {*/
            function registrationFormController($scope, $http) {
                // create a blank object to hold our form information
                // $scope will allow this to pass between controller and view
                $scope.userFormRegistration = {};

                // function to submit the form after all validation has occurred            
                $scope.submitForm = function (form) {
                    // check to make sure the form is completely valid
                    if (form.$valid) {
                        $scope.userFormRegistration = { actionname: "registration", email: $scope.userFormRegistration.email, password: $scope.userFormRegistration.password }
                        // start ajax call
                        $http({
                            method: 'POST',
                            url: 'Registration.php',
                            data: $.param($scope.userFormRegistration),  // pass in data as strings
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded'}  // set the headers so angular passing info as form data (not request payload)
                        })
                            .success(function (data) {
                                console.log(data);
                                if (!data.success) {
                                    // if not successful, bind errors to error variables
                                    $scope.errorRegistrationEmail = data.errors.email2;
                                    $scope.errorRegistrationPassword = data.errors.password;
                                    $scope.errorRegistrationActionname = data.errors.actionname;
                                    $scope.registrationMessage = data.message;
                                }
                                else {
                                    // if successful, bind success message to message
                                    $scope.message = data.message;
                                }
                            });
                        //end ajax call
                    }
                    else {
                        if (!$scope.userFormRegistration.email.$valid) {
                            var error = { message: "please enter valid email" };
                            $scope.errorRegistrationMessage = error.message;
                        }
                        else if (!$scope.userFormRegistration.password.$valid) {
                            var error = { message: "please enter valid password " };
                            $scope.errorRegistrationMessage = error.message;
                        }
                    }
                };
            };

Ваш совет пожалуйста.


person Rafael    schedule 24.11.2015    source источник
comment
вам нужно указать условие, когда и что вы хотите показать в классе, когда ввод является успешным или опасным   -  person Ubiquitous Developers    schedule 24.11.2015
comment
Вы уверены, что адрес электронной почты, который вы заполняете, действителен? Вы повторно используете имя где-то еще в форме?   -  person Carlos G.    schedule 24.11.2015


Ответы (1)


Свойства $valid и $invalid исходят из формы, а не из значения ввода. Вам нужен элемент формы с именем, затем также имя на входе, а затем используйте formName.inputName.$valid или $invalid.

person Leandro Zubrezki    schedule 24.11.2015
comment
Спасибо большое! проблема была в том, что форма не была объектом...=] - person Rafael; 26.11.2015