AngularJS动态需要在指令和表单验证中的属性 [英] AngularJS dynamic required attribute in directive and form validation

查看:109
本文介绍了AngularJS动态需要在指令和表单验证中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个指令,它接收一个元素应该是否来自REST api 。现在,当属性设置为required时,我似乎无法使表单无效。

I have a directive that receives whether an element should be required or not from a REST api. Right now, I can't seem to get the form to invalidate when an attribute is set to required.

因此,本质上我能够从下面的指令动态添加'required'属性,但它不会使表单无效。通过chrome看,我看到,即使存在必需的属性,$ error数组中的必需条目也不存在。

So, in essence I'm able to dynamically add the 'required' attribute from the directive below, but it doesn't invalidate the form. Looking through chrome I see that, even though the required attribute exists, a required entry in the $error array doesn't exist.

app.directive('requireiftrue', function ($compile) {
    return {
        require: '?ngModel',
        link: function (scope, el, attrs, ngModel) {
            if (!ngModel) {
                return;
            }

            if(attrs.requireiftrue==="true"){
                console.log('should require');
                el.attr('required', true);
                $compile(el.contents())(scope);
            }
            else{
                console.log('should not require');   
            }
        }
    };
});

这是 jsfiddle 来说明问题。并且,这是从我的其余API返回的示例JSON

Here's a jsfiddle to illustrate the problem. And, here's sample JSON returned from my rest API

{
    race: false,
    martialStatus: true,
}

编辑:虽然接受的答案让我感动启动和运行,我还有很多需要做的事情。

While the accepted answer got me up and running, I still had a good bit of finagling to do.

即:
1.解决延期承诺,确保我的表格实际上收到必要的字段以验证
2.观察我的'requireiftrue'属性

Namely: 1. Resolving a deferred promise to ensure that my form actually receives the required fields to validate 2. observing my 'requireiftrue' attribute

我的解决方案

模块配置:

function config($stateProvider) {
    $stateProvider

    .state('testState', {
        url: '/test/form',
        controller: 'TestCtrl',
        templateUrl: 'test/form/testForm.tpl.html',
        resolve: {
            formDefaultService: function getFormDefaults($q, dataservice) {
                // Set up a promise to return
                var deferred = $q.defer();
                var myData = dataservice.getFormDefaults();
                deferred.resolve(myData);

                return deferred.promise;
                //return 
            }
        },

        data: {
            pageTitle: 'Test Info'
        }
    });
}

最后收到api数据的指令/ HTML:

And, finally the directive / HTML that receives api data:

指令:

.directive('requireiftrue', function ($compile) {
    return {
        require: '?ngModel',
        link: function (scope, el, attrs, ngModel) {
            if (!ngModel) {
                return;
            }
            attrs.$observe('requireiftrue', function(value){ 
                if(value==="true"){
                    el.attr('required', true);
                    el.removeAttr('requireiftrue');
                    $compile(el[0])(scope);
                }
            });
        }
    };
});

HTML:

<input max="40"
requireiftrue={{defaults.validation.name}}
validNumber
id="name"
name="name"
type="text"
ng-model="test.name"
class="form-control">


推荐答案

你有两个问题:
第一个是el.contents()返回一个空数组。所以你应该做的第一件事就是把它改成el [0]。但如果el.contents()工作,你会遇到更严重的问题。您本来一直在尝试编译一个指令,该指令将自身作为指令导致无限循环(直到浏览器以任何方式崩溃)。
所以这里是修改后的代码:

You had two issues: The first is el.contents() returned an empty array. so The first thing you should do is change it to el[0]. But had el.contents() worked you would hav had a much more serious problem. You would have been trying to compile a directive that has itself as a directive which would lead to an infinite loop (well until the browser crashed any way). So here is the revised code:

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

app.directive('requireiftrue', function ($compile) {
    return {
        require: '?ngModel',
        link: function (scope, el, attrs, ngModel) {
            if (!ngModel) {
                return;
            }

            if(attrs.requireiftrue==="true"){
                console.log('should require');
                el.attr('required', true);
                el.removeAttr('requireiftrue');
                $compile(el[0])(scope);
            }
            else{
                console.log('should not require');   
            }
        }
    };
});

但是我应该注意到现在这个指令是一次性的。如果模型将发生变化,该指令将不再处理该元素。

I should note however that now this directive is a one-off. If the model will change, the directive will not be on the element any longer to deal with it.

这篇关于AngularJS动态需要在指令和表单验证中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆