我使用的是UI Bootstrap的日期选择器函数,我想获取传递到属性中的一个值。
// JS
$scope.myMaxDate = new Date();
<!-- HTML -->
<input datepicker-popup="MM/dd/yyyy" max-date="myMaxDate" />
我不明白为什么在这种情况下max-date
属性采用字符串而不是像{{myMaxDate}}
这样的表达式。它是如何掌握实际价值的?
更重要的是,我正在使用一个decorator来更改该指令中的一些数据,并希望访问该属性,但我得到的只是字符串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
方法。
因此,在您的代码中,要查看实际值,请使用:
console.log(scope.$eval(attrs.maxDate));
这也是指令不需要双花括号的原因。事实上,双花括号会引起问题,因为它会将myMaxDate
对象转换为字符串,从而丢失Date
对象的方法。
有关$eval
方法的更多信息,请参阅AngularJS Scope API
对于初学者来说,您完全覆盖了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);
};
};
....