Search code examples
javascriptangularjsangularjs-directiveangularjs-material

Angular Material - How to attach custom directive attribute to md-list-item element?


I'm trying to attach a custom directive to items in an ng-repeat list created with md-list/md-list-items, but because of the way angular material structures the md-list-item element when it's compiled in the DOM, nesting an absolute positioned button within for ng-click functionality, I can't find a way to actually attach the directive attribute to these as I could a normal md-button or similar.

I've tested the directive on other elements, where it's fine, and have tried attaching it directly to the md-list-item, but this obviously doesn't work.

Demonstrated in JSFiddle: http://jsfiddle.net/2f6qscrp/513/.

HTML:

<md-list-item view-employee employee="employee" ng-click="viewEmployee($index)" ng-repeat="employee in main.employees">

Solution

  • just add the event listener to the button tag like this

    angular.module('app').directive('viewEmployee', function() {
        return {
            restrict: 'A',
            scope: {
                employee: '='
            },
            link: function(scope, element, attrs) {
                element.find('button').bind('click', function(index, employee) {
                    alert('viewEmployee(): ' + scope.employee.forename + ' ' + scope.employee.surname);
                })
            }
        }
    })
    

    I've also updated your fiddle

    http://jsfiddle.net/2f6qscrp/514/