Avoid filter

Example of using $filter provider to avoid using the filter binding.

by Steven Lambert

HTML

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://code.angularjs.org/1.2.18/angular.min.js"></script>
<div ng-controller="myCtrl">
    <ul>
        <li ng-repeat="contact in contacts">
            <div my-directive="contact"></div>
        </li>
    </ul>
</div>

CSS

/* Styles go here */
input[type="text"] {
  margin-bottom: 10px;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  padding: 10px;
}

li:nth-child(2n+1) {
  background: #ccc;
}

.name {
  font-size: 18px;
  font-weight: bold;
}

.phone:before {
  content: '\260E';
  margin-right: 5px;
  line-height: 0.8;
  vertical-align: bottom;
}

.address:before {
  content: '\2709';
  font-size: 20px;
  margin-right: 9px;
  vertical-align: bottom;
  line-height: 0.6;
}

JavaScript

angular.module('myApp', []);

angular.module('myApp')
    .controller('myCtrl', function ($scope) {
    $scope.contacts = [{
        name: 'John Doe',
        phone: '(404) 776-8932',
        address: '1234 E 432 W, Orem, UT'
    }, {
        name: 'Sally Lang',
        phone: '(500) 412-5691',
        address: '931 Langford Dr, Saratoga Springs, UT'
    }, {
        name: 'Bob Thompson',
        phone: '(204) 830-2999',
        address: '1134 Main St, Lehi, UT'
    }, {
        name: 'Zack Pemberly',
        phone: '(300) 768-7661',
        address: '477 Hampton Ave APT 21, Draper, UT'
    }];
});

angular.module('myApp')
    .directive('myDirective', function ($filter) {
    return {
        scope: {
            contact: '=myDirective'
        },
        link: function ($scope, $element, $attrs) {
            // The contents of the list never change,
            // so there is no reason to add unnecessary
            // bindings.
            $element.html('<div class="name">' + $filter('uppercase')($scope.contact.name) +
                '</div>' +
                '<div class="phone">' + $scope.contact.phone +
                '</div>' +
                '<div class="address">' + $scope.contact.address +
                '</div>');
        }
    }
});