JSFiddle - React, Tailwind, and code Playground

AngularJS - displayCount directive - Experimenting with custom directives and scopes.

by Collin Donahue-Oponski

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.1/underscore-min.js"></script>
<div ng-app="fruit">
    <div ng-controller="FruitControl">
        
        <h1>{{apples.length}} apples.</h1>
        <div>Expected: The color of 1 of them is red.</div>
        <div>
            ---Actual:
            <span display-count list="apples" count-prop="'color'" count-val="'red'"></span>
        </div>
        
        <h1>{{bananas.length}} bananas.</h1>
        <div>Expected: The weight of 1 of them is 2.</div>
        <div>
            ---Actual: 
            <span display-count list="bananas" count-prop="'weight'" count-val="'2'"></span>
        </div>
        
    </div>
</div>

JavaScript

function FruitControl($scope) {
    $scope.apples = [{
        color: 'red',
        weight: 1
    }, {
        color: 'green',
        weight: 2
    }, {
        color: 'yellow',
        weight: 3
    }];

    $scope.bananas = [{
        color: 'red',
        weight: 2
    }, {
        color: 'green',
        weight: 2
    }, {
        color: 'yellow',
        weight: 1
    }];
}

angular.module('fruit', [])
.filter('count', function() {
    return function count(list, property, value) {
        return _(list).select(function(item) {
            return item[property] == value;
        }).length;
    };
})
.directive('displayCount', function() {
    return {
        template: 'The {{prop}} of {{list | count:prop:val}} of them is {{val}}.',
        compile: function() {
            return {
                pre: function($scope, $el, $attr) {
                    $scope.$watch($attr.list, function(newVal) {
                        console.log('new value for list: '+newVal);
                        $scope.list = newVal;
                    });
                    $scope.$watch($attr.countProp, function(newVal) {
                        console.log('new value for count prop: '+newVal);
                        $scope.prop = newVal;
                    });
                    $scope.$watch($attr.countVal, function(newVal) {
                        console.log('new value for count val: '+newVal);
                        $scope.val = newVal;
                    });
                }
            };
        }
    };
});