我刚开始接触AngularJS,并且正在将几个旧的jQuery插件转换为Angular指令。我想为我的(元素)指令定义一组默认选项,可以通过在属性中指定选项值来覆盖。
我查看了一些其他人是如何做到这一点的,而在angular-ui库中,ui.bootstrap.pagination似乎做了类似的事情。
首先,所有默认选项都定义在一个常量对象中:
.constant('paginationConfig', {
itemsPerPage: 10,
boundaryLinks: false,
...
})
然后,一个 getAttributeValue
的实用函数被附加到指令控制器上:
this.getAttributeValue = function(attribute, defaultValue, interpolate) {
return (angular.isDefined(attribute) ?
(interpolate ? $interpolate(attribute)($scope.$parent) :
$scope.$parent.$eval(attribute)) : defaultValue);
};
最后,在链接函数中使用它作为读取属性的方法。
.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
这样的实用函数,并以这种方式解析选项?我很感兴趣了解人们在这个常见任务上有哪些不同的策略。
此外,额外奖励,我不清楚为什么需要interpolate
参数。
=?
自1.1.x版本起可用。 - Michael Radionovtrue
或false
作为值,那么你(我认为)希望使用例如$scope.hasName = angular.isDefined($scope.hasName) ? $scope.hasName : false;
。 - Paul D. Waite=?
,但不适用于单向绑定,@?
。 - Justus Romijnlink
函数中设置?根据我的理解,在link
期间进行赋值可以避免$scope.$apply()
周期,是吗? - Augustin Riedinger