Angular JS Magazine

duminică, 28 septembrie 2014

Custom Directive - Order List With Marker Type

In Creating a Simple Custom Directive you saw how to write a simple directive for displaying an array as an HTML ordered list. An order list supports several attributes that allows us to customize its aspect. Per example, the type attribute allows us to indicate the kind of marker to use in the list: (1, A, a, I, i). The below tip shows you how to add the type attribute in a directive:

<!DOCTYPE html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="../angular/angular.min.js"></script>
    <style type="text/css">
        angular.module("appModule", [])
                .controller("appCtrl", function ($scope) {
                    $scope.players = [
                        { name: 'Nadal, Rafael (ESP)'},
                        { name: 'Djokovic, Novak (SRB)'},
                        { name: 'Federer, Roger (SUI)'},
                        { name: 'Wawrinka, Stan (SUI)'},
                        { name: 'Ferrer, David (ESP)'},
                        { name: 'Tsonga, Jo-Wilfried (FRA)'},
                        { name: 'Simon, Gilles (FRA)'},
                        { name: 'Mayer, Leonardo (ARG)'},
                        { name: 'Murray, Andy (GBR)'},
                        { name: 'Dimitrov, Grigor (BUL)'},
                        { name: 'Cilic, Marin (CRO)'}
                .directive("orderedList", function () {
                    return function (scope, element, attrs) {
                        var data = scope[attrs["orderedList"]];
                        var marker = attrs["markerType"];
                        if (angular.isArray(data)) {
                            var listElem = angular.element("<ol type="+marker+">");
                            for (var i = 0; i < data.length; i++) {
<div ng-app="appModule" ng-controller="appCtrl">

    <h4>Creating a Simple Custom Directive - List Directive</h4>

    <div ordered-list="players" marker-type="i"></div>