Last Updated: February 25, 2016
·
1.568K
· mdonkers

AngularJS Directives - access attribute property directly

With Angular directives it is possible to create your own HTML tags and add functionality to them. Angular documentation describes how to use HTML attributes to specify which value to fetch from the scope, or which function to execute.
It is also possible to use an attribute value directly (without linking to the scope), however this is less obvious from the docs. I hope the sample below clarifies how it can be done.

I wanted to specify the field-name for ordering as attribute, and in the directive code use this value directly. As you see, by specifying "orderBy" with "@", you can later use the "orderBy" value directly inside the partial. Should you want to use it as value inside the HTML, add the {{ }} brackets, now its specified without brackets because its inside the "ng-repeat" attribute.

index.html

<stats-list list-type="topDuration" order-by="duration"></stats-list>
<stats-list list-type="latest" order-by="start"></stats-list>

directive.js

myApp.directive('statsList', function () {
    return {
        restrict: 'E',
        scope: {
            items: '=listType',
            orderBy: '@'
        },
        templateUrl: 'partials/partial1.html'
    };
});

partial1.html

<table class="table table-condensed">
    <thead>
    <tr>
        <th>Sensor Id</th>
        <th>Start</th>
        <th>Duration</th>
    </tr>
    </thead>
    <tbody>
    <tr ng-repeat="item in items | orderBy:'value.' + orderBy:reverse=true">
        <td>{{item.value.sensorId}}</td>
        <td>{{item.value.start | date:'dd/MM @ H:mm'}}</td>
        <td>{{item.value.duration | msToSec | number | secAppendix}}</td>
    </tr>
    </tbody>
</table>