角度指令字段不需要括号 [英] Angular directive fields not require brackets

查看:34
本文介绍了角度指令字段不需要括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 UI Bootstrap 的 datepicker 函数,我想获取传递给属性的值之一.

I'm using UI Bootstrap's datepicker function and I'd like to get ahold of one of the values passed into an attribute.

// JS
$scope.myMaxDate = new Date();

<!-- HTML -->
<input datepicker-popup="MM/dd/yyyy" max-date="myMaxDate" />

我不明白为什么在这种情况下 max-date 属性采用字符串而不是像 {{myMaxDate}} 这样的表达式.它是如何获得实际价值的?

I don't understand why in this case the max-date attr takes a string rather than an expression like {{myMaxDate}}. How is it getting a hold of the actual value?

更重要的是,我正在使用装饰器来更改此指令中的一些数据,并想访问此属性,但我得到的只是字符串 myMaxDate.

What's more, I'm using a decorator to alter some data from this directive and would like to access this attribute but all I get is the string myMaxDate.

    $provide.decorator("datepickerPopupDirective", ["$delegate", function($delegate) {
        // get references to the directive and old link function
        var directive = $delegate[0];
        var link = directive.link;

        // create a new link function using compile
        directive.compile = function() {
            // the new link function we want to return
            return function(scope, element, attrs, ngModelCtrl) {
                console.log(attrs.maxDate); // 'myMaxDate'

                // invoke the old link function
                link.apply(this, arguments);
            };
        };

推荐答案

回答关于 datepicker-popup 指令如何找到 max-date 的实际值的问题> 属性,它很可能使用 scope$eval 方法.

To answer your question on how the datepicker-popup directive finds the actual value of the max-date attribute, it most likely uses the $eval method of the scope.

所以在你的代码中,查看实际值使用:

So in your code, to see the actual value use:

 console.log(scope.$eval(attrs.maxDate));

这也是指令不需要双大括号的原因.事实上,双大括号会导致问题,因为它会将您的 myMaxDate 对象转换为字符串,从而丢失 Date 对象的方法.

This is also why the directive doesn't require double curly brackets. In fact double curly brackets will cause problems because it will convert your myMaxDate object to a string and consequently lose the Date object's methods.

有关 $eval 方法的更多信息,请查看 AngularJS 范围 API

For more information on the $eval method look at the AngularJS Scope API

这篇关于角度指令字段不需要括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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