ng-show in angular的问题

时间:2014-07-15 22:00:20

标签: javascript angularjs angularjs-directive

在验证此示例中的第一个字段时,我无法显示错误消息。

只有第二个字段显示该消息。 你能告诉我我的代码有什么问题吗?

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>

2 个答案:

答案 0 :(得分:1)

请见http://plnkr.co/edit/UeX6eAyjDPmqLagRQZmy?p=preview 在您的模板中,您已经不必要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]$/">'
        };
    });

答案 1 :(得分:1)

问题是name在指令的模板中是硬编码的。

要解决此问题,请使用模板函数动态地将name属性添加到模板字符串中:

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

注意:form validation in Angular

需要name属性
相关问题