gpt4 book ai didi

angularjs - 如何在 Angular JS 中访问指令参数?

转载 作者:行者123 更新时间:2023-12-02 07:41:18 25 4
gpt4 key购买 nike

我对 Angular 还很陌生,遇到了一个小问题。我有这个简单的日期选择器指令,它可以工作

app.directive('datepicker', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel){
$(elem).datepicker({
onSelect: function(dateText){
scope.$apply(function(){
ngModel.$setViewValue(dateText);
});
}
});
}
}
});

我用来调用它的 html 是

<input datepicker data-ng-model="day.date" readonly/> 

我希望能够更改日期选择器调用的 onSelect 函数 - 希望是这样的。

<input datepicker="myOnSelectMethod()" data-ng-model="day.date" readonly/>

然后指令看起来像这样

app.directive('datepicker', function() {
return {
require: 'ngModel',
link: function(scope, elem, attr, ngModel){
if(myOnSelectMethod is defined){ //how do I access myOnSelectMethod here?
$(elem).datepicker({
onSelect: myOnSelectMethod();
});
}
else{ //proceed as before
$(elem).datepicker({
onSelect: function(dateText){
scope.$apply(function(){
ngModel.$setViewValue(dateText);
});
}
});
}
}
}
});

所以我的问题是:如何从链接函数访问我想要执行的新 onSelect 函数?

查看文档和其他问题,这似乎应该是可能的,但我无法使其发挥作用。我想出了一个丑陋的解决方法,通过使用 ng-click 来激活给定元素上的日期选择器,但我想了解如何在可能的情况下完成这项工作。谢谢!

最佳答案

您可以这样检查:

if( attr["datepicker"] == "myOnSelectMethod" && 
typeof myOnSelectMethod === "function" ){
// ...
}

或者甚至:

if( typeof scope[attr["datepicker"]] === "function" ){ // Instead of `scope` 
// ... // may be any other object,
} // `window` for example

关于angularjs - 如何在 Angular JS 中访问指令参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18597403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com