我有以下脚本,其中 dateTimePicker
作为 AngularJS 指令:
(function () {
'use strict';
var module = angular.module('feedApp');
module.directive('datetimepicker', [
'$timeout',
function ($timeout) {
return {
require: '?ngModel',
restrict: 'EA',
scope: {
options: '@',
onChange: '&',
onClick: '&'
},
link: function ($scope, $element, $attrs, controller) {
$($element).on('dp.change', function () {
$timeout(function () {
var dtp = $($element).data('DateTimePicker');
controller.$setViewValue(dtp.date().format('MM/DD/YYYY HH:mm'));
$scope.onChange();
});
});
$($element).on('click', function () {
$scope.onClick();
});
controller.$render = function () {
if (!!controller) {
if (controller.$viewValue === undefined) {
controller.$viewValue = null;
}
else if (!(controller.$viewValue instanceof moment)) {
controller.$viewValue = moment(controller.$viewValue);
}
$($element).data('DateTimePicker').date(controller.$viewValue);
}
};
$($element).datetimepicker($scope.$eval($attrs.options));
}
};
}
]);
})();
我想使用 TypeScript 重写它。这是我现在的代码:
namespace feedApp {
'use strict';
DateTimePicker.$inject = ['$timeout'];
function DateTimePicker($timeout: ng.ITimeoutService): ng.IDirective {
var directive = <ng.IDirective>{
require: '?ngModel',
restrict: 'EA',
scope: {
options: '@',
onChange: '&',
onClick: '&'
},
link: link
};
function link(scope: ng.IScope, element: JQuery, attrs: ng.IAttributes, controller: ng.INgModelController): void {
$(element).on('dp.change', function () {
$timeout(function () {
var dtp = $(element).data('DateTimePicker');
controller.$setViewValue(dtp.date().format('MM/DD/YYYY HH:mm'));
scope.onChange();
});
});
$(element).on('click', function () {
scope.onClick();
});
controller.$render = function () {
if (!!controller) {
if (controller.$viewValue === undefined) {
controller.$viewValue = null;
}
else if (!(controller.$viewValue instanceof moment)) {
controller.$viewValue = moment(controller.$viewValue);
}
$(element).data('DateTimePicker').date(controller.$viewValue);
}
};
$(element).datetimepicker(scope.$eval(attrs.options));
}
return directive;
}
angular.module("feedApp")
.directive("datetimepicker", DateTimePicker);
}
我没有使用 TypeScript 的经验,并且我真的不知道使用 TS 更改 $(element).on
等 jQuery 元素的最佳实践是什么。如何使用
scope: {
options: '@',
onChange: '&',
onClick: '&'
},
TypeScript link
函数内部?预先感谢您的帮助。
最佳答案
使用bindToController访问指令 Controller 内的范围变量。 为了更好地构建/理解,请在不同的文件中声明指令的不同组件,例如 Controller 应该位于唯一的文件中,html应该有自己的文件等。
请引用Directive testing问题和typescript github sample project了解更多相关信息。
如果您需要更多说明,请告诉我。
问候
阿杰
关于javascript - 如何使用 TypeScript 解决 AngularJS 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37045228/