将函数表达式存储在angularjs指令的link函数中,并通过ng-click使用它

Storing a function expression inside a link function of an angularjs directive and use it via ng-click

本文关键字:函数 ng-click link 存储 表达式 angularjs 指令      更新时间:2023-09-26

我有以下angularjs指令,我希望能够使用ng-click在property-slider.html中执行showMap()。我错过了什么?

(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);
            }
        };
    }
})();

两个问题....函数需要分配给作用域,而不需要在$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);
}

除了使用ng-click,您还可以将您的方法保留为指令的"private",并检测元素上的事件:

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