Wednesday, May 15, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  34] [ 3]  / answers: 1 / hits: 88470  / 11 Years ago, fri, september 13, 2013, 12:00:00

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.


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,
...
})

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);
...
}
});

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.


More From » angularjs

 Answers
17

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; }
},
...
}
});

[#75710] Thursday, September 12, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mckinleykeyshawnb

Total Points: 281
Total Questions: 99
Total Answers: 111

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;