角指令使用默认选项 [英] Angular directive with default options
问题描述
我刚开始用angularjs,和我的工作有关转换几个老jQuery插件,以角指令。我想定义一组默认选项为我(元)指令,它可以通过在属性指定选项值覆盖。
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.
我已经有别人这样做的方式看看周围,并在角UI 库中的<一个href=\"https://github.com/angular-ui/bootstrap/blob/master/src/pagination/pagination.js\">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.
此外,作为奖励,我不清楚为什么插值
是必需的参数。
Also, as a bonus, I'm not clear why the interpolate
parameter is required.
推荐答案
您可以使用编译功能 - 读出的属性,如果没有设置他们 - 与默认值填充它们
You can use compile function - read attributes if they are not set - fill them with default value.
.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; }
},
...
}
});
这篇关于角指令使用默认选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!