GibboK
GibboK

Reputation: 73898

Issue with ng-show in angular

I cannot show an error message when validation the first field in this example.

Only the second field show up the message. Could you tell me what is wrong in my code?

http://plnkr.co/edit/OXtrm9skUUe1D6e8F8gw?p=preview

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

    app.directive('gaTime', function () {
        var EMAIL_REGX = /^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/;
        return {
            restrict: 'E',
            scope: {
                timeInfo: '=info' // Unique to directive scope
            },
            template: '<input type="text" name="operativeToTime" data-ng-model="timeInfo" data-ng-required="false" data-ng-pattern="/^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/">'
        };
    });

app.controller('MainCtrl', function($scope) {
    // Default values
    $scope.operativeFromTime = '00:00:00';
    $scope.operativeToTime = '23:59:59';
});


  <form name="addDeviceForm" data-ng-submit="submitForm(addDeviceForm.$valid)" novalidate>
            <data-ga-time name="operativeFromTime" info="operativeFromTime"></data-ga-time>
            <span data-ng-show="addDeviceForm.operativeFromTime.$invalid">+++ INVALID FROM.</span>
            <br>

            <data-ga-time name="operativeToTime" info="operativeToTime"></data-ga-time>
            <span data-ng-show="addDeviceForm.operativeToTime.$invalid">+++ INVALID TO.</span>
  </form>

Upvotes: 1

Views: 48

Answers (2)

Michael Kang
Michael Kang

Reputation: 52837

The issue is that name is hard-coded in the directive's template.

To fix this, use a template function to add the name attribute to your template string dynamically:

template: function(tElem, tAttrs){

    return '<input type="text" name="' + tAttrs.name +
           '" data-ng-model="timeInfo" data-ng-required="false" 
            data-ng-pattern="/^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/">';
}

Demo Plunker

Note: the name attribute is required for form validation in Angular

Upvotes: 1

sylwester
sylwester

Reputation: 16498

Please see here http://plnkr.co/edit/UeX6eAyjDPmqLagRQZmy?p=preview in your template you've got unnecessarily name="operativeToTime"

 app.directive('gaTime', function () {
        var EMAIL_REGX = /^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/;
        return {
            restrict: 'E',
            replace: 'true',
            scope: {
                timeInfo: '=info' ,// Unique to directive scope

            },
            template: '<input type="text"  data-ng-model="timeInfo" data-ng-required="false" data-ng-pattern="/^(?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9]$/">'
        };
    });

Upvotes: 1

Related Questions