1

I have the following angularjs directive and I would like to be able to use ng-click to execute showMap() inside property-slider.html. What am I missing?

(function() {
    'use strict';

    angular
        .module('myapp')
        .directive('propertySlider', propertySlider);

    function propertySlider($timeout) {

        return {
            restrict: 'E',
            templateUrl: 'property-slider.html',
            replace: true,
            scope: {
                property: '=',
                photos: '='
            },
            link: function(scope, element) {
                $timeout(function(){

                    var slider = element.flickity({
                        cellAlign: 'left',
                        cellSelector: '.gallery-cell',
                        lazyLoad: true,
                        wrapAround: true,
                        initialIndex: 1
                    });

                    var showMap = function(){
                        slider.flickity('select', 0);
                    };

                },500);

            }
        };

    }

})();
Gab
  • 2,216
  • 4
  • 34
  • 61

2 Answers2

1

Two issues....function needs to be assigned to scope and you don;t need to create it inside $timeout

link: function(scope, element) {

     scope.showMap = function () {
         element.flickity('select', 0);
     };

     $timeout(function () {

          element.flickity({
             cellAlign: 'left',
             cellSelector: '.gallery-cell',
             lazyLoad: true,
             wrapAround: true,
             initialIndex: 1
         });

     }, 500);
}
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • Thank you it works except that if I set the function expression outside the $timeout it's undefined when it's executed. – Gab Sep 26 '15 at 00:14
1

Instead of using ng-click you can also keep your method "private" to your directive and detect the event on the element :

link: function(scope, element, attrs) {
    element.on('click', function(e) {
        showMap();
    });

    var showMap = ...
}
c4k
  • 4,270
  • 4
  • 40
  • 65