Note that there are some explanatory texts on larger screens.

plurals
  1. POAngular directive with default options
    text
    copied!<p>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.</p> <p>I've had a look around for the way others have done this, and in the <a href="http://angular-ui.github.io">angular-ui</a> library the <a href="https://github.com/angular-ui/bootstrap/blob/master/src/pagination/pagination.js">ui.bootstrap.pagination</a> seems to do something similar.</p> <p>First all default options are defined in a constant object:</p> <pre><code>.constant('paginationConfig', { itemsPerPage: 10, boundaryLinks: false, ... }) </code></pre> <p>Then a <code>getAttributeValue</code> utility function is attached to the directive controller:</p> <pre><code>this.getAttributeValue = function(attribute, defaultValue, interpolate) { return (angular.isDefined(attribute) ? (interpolate ? $interpolate(attribute)($scope.$parent) : $scope.$parent.$eval(attribute)) : defaultValue); }; </code></pre> <p>Finally, this is used in the linking function to read in attributes as</p> <pre><code>.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); ... } }); </code></pre> <p>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 <code>getAttributeValue</code> and parse options in this way? I'm interested to find out what different strategies people have for this common task.</p> <p>Also, as a bonus, I'm not clear why the <code>interpolate</code> parameter is required.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload