Angular 指令字段不需要括号

Angular directive fields not require brackets

我正在使用 UI Bootstrap 的日期选择器函数,我想获取传递到属性中的值之一。

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

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

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

此外,我正在使用装饰器更改此指令中的一些数据,并想访问此属性,但我得到的只是字符串 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);
            };
        };

首先,您要完全覆盖 compile。这会产生潜在的问题。

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

        directive.compile = function() {

            var link = compile.apply(this, arguments); 

            // 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 方法。

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

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

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

有关 $eval 方法的更多信息,请参阅 AngularJS Scope API