带有默认选项的 AngularJS 指令 [英] AngularJS directive with default options
问题描述
我刚刚开始使用 angularjs,并且正在将一些旧的 JQuery 插件转换为 Angular 指令.我想为我的(元素)指令定义一组默认选项,可以通过在属性中指定选项值来覆盖这些选项.
I'm just starting with angularjs, and am working on converting a few old JQuery plugins to Angular directives. I'd like to define a set of default options for my (element) directive, which can be overridden by specifying the option value in an attribute.
我查看了其他人的做法,在 angular-ui 库中,
I've had a look around for the way others have done this, and in the angular-ui library the ui.bootstrap.pagination seems to do something similar.
首先在一个常量对象中定义所有默认选项:
First all default options are defined in a constant object:
.constant('paginationConfig', {
itemsPerPage: 10,
boundaryLinks: false,
...
})
然后一个 getAttributeValue
实用函数被附加到指令控制器:
Then a getAttributeValue
utility function is attached to the directive controller:
this.getAttributeValue = function(attribute, defaultValue, interpolate) {
return (angular.isDefined(attribute) ?
(interpolate ? $interpolate(attribute)($scope.$parent) :
$scope.$parent.$eval(attribute)) : defaultValue);
};
最后,这在链接函数中用于读取属性
Finally, this is used in the linking function to read in attributes as
.directive('pagination', ['$parse', 'paginationConfig', function($parse, config) {
...
controller: 'PaginationController',
link: function(scope, element, attrs, paginationCtrl) {
var boundaryLinks = paginationCtrl.getAttributeValue(attrs.boundaryLinks, config.boundaryLinks);
var firstText = paginationCtrl.getAttributeValue(attrs.firstText, config.firstText, true);
...
}
});
对于像想要替换一组默认值这样的标准设置,这似乎是一个相当复杂的设置.有没有其他常见的方法可以做到这一点?或者总是这样定义一个实用函数比如getAttributeValue
并解析选项是正常的吗?我很想知道人们对这项常见任务有哪些不同的策略.
This seems like a rather complicated setup for something as standard as wanting to replace a set of default values. Are there any other ways to do this that are common? Or is it normal to always define a utility function such as getAttributeValue
and parse options in this way? I'm interested to find out what different strategies people have for this common task.
另外,作为奖励,我不清楚为什么需要 interpolate
参数.
Also, as a bonus, I'm not clear why the interpolate
parameter is required.
推荐答案
您可以使用 compile
功能 - 如果未设置属性,则读取它们 - 使用默认值填充它们.
You can use compile
function - read attributes if they are not set - fill them with default values.
.directive('pagination', ['$parse', 'paginationConfig', function($parse, config) {
...
controller: 'PaginationController',
compile: function(element, attrs){
if (!attrs.attrOne) { attrs.attrOne = 'default value'; }
if (!attrs.attrTwo) { attrs.attrTwo = 42; }
},
...
}
});
这篇关于带有默认选项的 AngularJS 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!