带有默认选项的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 库中, ui.bootstrap.pagination 似乎在做类似的事情.
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屋!