比较angularjs指令中的两个字段 [英] Compare two fields in angularjs directive

查看:78
本文介绍了比较angularjs指令中的两个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建指令,可用于比较多个项目中的两个字段。

I am trying to create directive which can be used to compare two fields in multiple projects.

MarkUp:

<div class="form-group">
<input  ng-model="user.password"  type="password" name="password"  />
</div>
<div class="form-group">
<input  ng-model="user.confpassword" ng-compare="password" name="confpassword" type="password"  />
<p ng-show="registrationform.password.$error.ngcompare" class="help-block">Password's don't match</p>

指令:

 "use strict";
 angular.module('app.directive.ngCompare', []).directive('ngCompare', function () {

return {
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelController)
    {
           ngModelController.$parsers.unshift(function (viewvalue) {
            console.log(scope); // doesnot contain password field object
            console.log(viewvalue); // gives me value of confpassword field
            console.log(scope[attrs.ngCompare]); // undefined
        });


    }

}});

我还没有完成我的指令编写,但是在开发过程中我控制范围时我没有得到第一个值密码,但我得到confpassword.i的价值我在我的主应用程序中包括这个direcitive为'app.directive.ngCompare'。因为我没有得到密码的价值。

I have not completed writing my directive but , during development when i console scope i dont get value of first password but i get value of confpassword.i am including this direcitive in my main app as 'app.directive.ngCompare'.Is it because of that i dont get value of password.

我正在使用角度版本1.3.9。我知道有很多类似的指令,但我需要逐步弄清楚它们是如何运行的,所以从头开始创建。有没有其他方法可以使用angularjs技术而不是jquery方法来获取密码的价值。

I am using angular version 1.3.9. I know there are many similar directives out there but i need to figure out step by step how they run so started creating from scratch.Is there any other way to get value of password using angularjs techiques rather than jquery methods.

推荐答案

到目前为止给出的答案的问题是它们都创建了一个隔离范围。这意味着您不能在相同的输入或另一个指令上使用其他指令。

The problem with the answers given so far is that they all create an isolate scope. This means you couldn't use additional directives on the same input or on another directive.

可以通过修改上述内容来解决此问题:

That can be fixed by modifying the above as follows:

.directive("compareTo", function() {
    return {
        require: "ngModel",
        link: function(scope, element, attrs, ctrl) {

            ctrl.$validators.compareTo = function(val) {
                return val == scope.$eval(attrs.compareTo);
            };

            scope.$watch(attrs.compareTo, function() {
                ctrl.$validate();
            });
        }
    };
});

这篇关于比较angularjs指令中的两个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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