如何访问参数的指令? [英] How to access arguments in a directive?

查看:113
本文介绍了如何访问参数的指令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义的指令,像这样:

I've defined a directive like so:

angular.module('MyModule', [])
    .directive('datePicker', function($filter) {
        return {
            require: 'ngModel',
            link: function(scope, elem, attrs, ctrl) {
                ctrl.$formatters.unshift(function(modelValue) {
                    console.log('formatting',modelValue,scope,elem,attrs,ctrl);
                    return $filter('date')(modelValue, 'MM/dd/yyyy');
                });
                ctrl.$parsers.unshift(function(viewValue) {
                    console.log('parsing',viewValue);
                    var date = new Date(viewValue);
                    return isNaN(date) ? '' : date;
                });
            }
        }
    });

对此我申请一个元素,像这样:

Which I apply to an element like so:

<input type="text" date-picker="MM/dd/yyyy" ng-model="clientForm.birthDate" />

每当我在日期选择器属性添加到一个元素我的指令被触发,但我想知道如何访问属性的值( MM / DD / YYYY )我的指令JS里面,这样我可以删除 $过滤器旁边的常数。我不知道如果有我可以访问的变量来提供这一点。

My directive gets triggered whenever I add the date-picker attribute to an element, but I want to know how to access the attribute's value (MM/dd/yyyy) inside my directive JS so that I can remove that constant beside $filter. I'm not sure if any of the variables I have access to provide this.

推荐答案

只需直接将它的 ATTRS

return $filter('date')(modelValue, attrs.datePicker);


顺便说一句,如果你使用的唯一过滤器是日期,那么你可以直接注入是:


BTW, if the only filter you're using is date, then you can inject that directly:

.directive('datePicker', function (dateFilter) {
    // Keep all your code, just update this line:
    return dateFilter(modelValue, attrs.datePicker || 'MM/dd/yyyy');
    // etc.
}

这篇关于如何访问参数的指令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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