在浏览了 Angularjs 的文档后,我希望有人可以帮助澄清我面临的问题。我正在编写一个包含 jQuery 插件的指令,但我不确定这样的最佳实践。它本质上是一个移植,使 jquery 插件能够与 Angular 很好地配合,并使其更加参数化和可扩展。
我想要移植的插件主要是 DOM 操作(像大多数 jQuery 库一样)来处理表单;如果需要,我可以发布更多代码,但我主要想知道最佳实践或将其构建为 Angular 时需要注意的事项。
谢谢!!
到目前为止我的指令:
'使用严格';
/**
* @ngdoc directive
* @name goodStewardApp.directive:card
* @description
* # card
*/
angular.module('goodStewardApp')
.directive('card', function() {
return {
template: "<card> What is this madness? </card>",
restrict: 'A',
link: function() {
// jQuery function here
};
};
});
最佳答案
如果插件非常简单并且没有任何回调,那么代码就非常简单:
angular.module('goodStewardApp').directive('card', function() {
return {
template: "<card> What is this madness? </card>",
restrict: 'A',
link : function(scope, element, attr) {
$(element).plugin();
}
};
});
但是,如果插件有任何自定义事件或回调,那么您需要将它们包装在 $apply()
中:
angular.module('goodStewardApp').directive('datepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
var options = scope.$eval(attrs['datepicker']);
$(function () {
element.datepicker({
dateFormat: options['dateFormat'],
onSelect: function (date) {
scope.$apply(function () {
ngModelCtrl.$setViewValue(date);
});
}
}).prop('readonly', true).addClass('datepicker');
});
}
};
});
关于javascript - 来自 jquery 插件的 angularjs 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24128745/