指令和控制器angularjs之间的通信

时间:2015-10-05 08:04:50

标签: angularjs controller directive

我想知道当电子邮件已经存在时是否有可能向用户发送某种错误消息。 我有这样的指示。 :

(function() {

    angular
        .module('app')
        .directive('emailNotUsed',emailNotUsed);

    emailNotUsed.$inject = ['$http', '$q'];

function emailNotUsed ($http, $q) {
    return {

        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$asyncValidators.emailNotUsed = function(modelValue, viewValue) {
                return $http.post('/email',viewValue).then(function(response) {
                    console.log(response);
                    return response.data == true ? /*$q.reject(response.data.errorMessage)*/  console.log("Show Error Message"): true;

                   // console.log(response);
                });
            };
        }
    };
    }
}());

如您所见,这会在控制台中返回Show error。但是可以将此值传递给寄存器控制器吗?并将值设置为true或false?

(function () {
    'use strict';

    angular
        .module('app')
        .controller('RegisterController', RegisterController);

    RegisterController.$inject = ['UserService', '$http','$q' ];
    function RegisterController(UserService, $http,$q) {
        var vm = this;

        vm.register = register;


        function register() {

           vm.dataLoading = true;
           UserService.Create(vm.user)

        }

    }

})();

或者我可以直接将错误消息发送到html中。

<div class="container" ng-controller="RegisterController as vm">
    <div class="col-md-6 col-md-offset-3">

        <div ng-show="vm.error" class="alert alert-danger">{{vm.error}}</div>
        <form name="form" ng-submit="!form.$pending && form.$valid && vm.register()" role="form">




            <div>
                <label for="email">Email</label>
                <input type="text" name="email" id="email" class="form-control" ng-model="vm.user.email" email-not-used ng-model-options="{ debounce: 500 }" required  >
            </div>


            <div class="form-actions">
                <button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-primary">Register</button>
                <a href="#/login" class="btn btn-link">Cancel</a>
            </div>
        </form>
    </div>
</div>

我的解决方案

在经历了很多艰难的挣扎之后,我找到了解决问题的方法。

我将emailNotUsed指令修改为emailValidator。

(function() {
    angular
        .module('app')
        .directive('emailValidator',emailValidator);

    emailValidator.$inject = ['$q', '$timeout','$http'];

    function emailValidator ($q, $timeout,$http){

        return {

            require: 'ngModel',
            link: function(scope, element, attrs, ngModel) {
                ngModel.$asyncValidators.email = function(modelValue, viewValue) {

                    var deferred = $q.defer();
                    DoesEmailExist()

                    function DoesEmailExist () {

                        $http.post('/email',viewValue).then(function(response) {

                            if (response.data==true) {
                                console.log('Email does exist')
                                deferred.reject();
                            }else {
                                deferred.resolve();
                            }
                        });

                    };

                    console.log(deferred.promise)
                    return deferred.promise;
                };
            }
        }


    }
}());

在registration.html中,我添加了这个:

    <div class="form-group" ng-class="{ 'has-error': form.email.$dirty && form.email.$invalid }">

        <label for="email"> Email</label>
        <input type="text" ng-model="signup.email" ng-model-options="{ debounce: 500 }" name="email" id="email" class="form-control" required email-validator>


        <div  class="help-block" ng-messages="form.email.$error" ng-if="form.email.$dirty">
            <p ng-message="required">Your name is required.</p>
            <div ng-message="email" class="help-block" >email already in use</div>
        </div>

2 个答案:

答案 0 :(得分:0)

您可以直接在视图中设置错误消息。绑定到$ scope.form.email.emailNotUsed。

<div>
    <label for="email">Email</label>
    <input type="text" name="email" id="email" class="form-control" ng-model="vm.user.email" email-not-used ng-model-options="{ debounce: 500 }" required  >
    <span ng-show="form.email.emailNotUsed">Email is already in use!</span>
</div>

答案 1 :(得分:0)

是的,您可以直接在HTML中显示错误消息。

试试这个,

在HTML中,

<form name="form" ng-submit="!form.$pending && form.$valid && vm.register()" role="form">
            <div>
                <label for="email">Email</label>
                <input type="text" name="email" id="email" class="form-control" ng-model="vm.user.email" email-not-used ng-model-options="{ debounce: 500 }" required  >
                 <span ng-show="form.email.$invalid && form.email.$dirty">Email is already in use!</span>
                 <span ng-show="form.email.$valid && form.email.$dirty">Email available!</span>
            </div>


            <div class="form-actions">
                <button type="submit" ng-disabled="form.$invalid || vm.dataLoading" class="btn btn-primary">Register</button>
                <a href="#/login" class="btn btn-link">Cancel</a>
            </div>
        </form>

在app.js中,

var app = angular.module('app', []);



    app.directive('emailNotUsed',emailNotUsed);

    emailNotUsed.$inject = ['$http', '$q'];

function emailNotUsed ($http, $q) {
    return {

        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$asyncValidators.emailNotUsed = function(modelValue, viewValue) {
                  var data='';
                  if (viewValue=='abc@xyz.com'){
                      ngModel.$setValidity('valid', false);
                       scope.form.email.$setValidity('email', false);

                  }else{
                       ngModel.$setValidity('valid', true);
                       scope.form.email.$setValidity('email', true);
                  }

                return data;
        }
    }
    }
}


    app.controller('RegisterController', RegisterController);

    RegisterController.$inject = ['$scope', '$http','$q' ];
    function RegisterController($scope, $http,$q) {
        var vm = this;
    $scope.name = 'abc@xyz.com email is already in use ';
        vm.register = register;


        function register() {

           vm.dataLoading = true;
           UserService.Create(vm.user)

        }

    }

希望这会有所帮助。