我正在为我的 Angular 应用程序创建一个具有基本功能的自定义指令。除了该指令之外,我还想添加一个类似于附加设置选项的属性,以便在提到属性时我可以添加扩展功能。
我想做这样的事情:
<div use-date-picker this-ngmodel="formData.dt" today></div>
在上面的自定义指令中,我希望日期选择器输入字段仅在添加 today
属性时才具有今天的日期。现在,我不知道如何在该指令中定义该函数,因此仅当“today”属性添加到调用该指令的 DIV 时,它才会添加默认的今天日期。我尝试了这个,但它不起作用:
app.directive('useDatePicker', function() {
return {
restrict: 'A',
replace:true,
scope: {
thisNgmodel: '='
},
template: '<div class="input-group">' +
'<input type="text" class="form-control" readonly="readonly" name="dt" ng-model="thisNgmodel" datepicker-popup="{{format}}" is-open="datepickers.dt" datepicker-options="dateOptions" ng-required="true" close-text="Close" />' +
'</div> ',
link: function(scope, element, attr) {
console.log(scope.thisNgmodel);
console.debug(scope);
// Here I am trying to add the default Today's date if today attribute is added
if (element.attr('today')) {
$scope.today();
}
},
controller: function($scope) {
//DatePicker
$scope.today = function() {
$scope.thisNgmodel = new Date();
};
// ....... etc.. etc.. with other controller settings .......
}
};
});
如果提到属性,我可以向指令模板添加额外的函数吗?上面的代码我做错了什么?
最佳答案
指令的
controller属性与module.controller
不同。它的主要目的是与其他指令的 api 进行通信...引用自 angularjs 文档
Best Practice: use controller when you want to expose an API to other directives. Otherwise use link
您可以在链接功能中将模型的值设置为新日期...
if (element.attr('today')) {
scope.thisNgmodel = new Date();
}
关于javascript - 如何根据指令中的属性设置添加附加功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22554407/