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

标签 javascript angularjs angularjs-directive angularjs-scope flickity

我有以下 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);
}

关于javascript - 将函数表达式存储在 angularjs 指令的链接函数中并通过 ng-click 使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792240/

相关文章:

javascript - 从数组中检索数据,从 AngularJs 中的特定第 n 项开始

javascript - 嵌套指令 - 无法将参数从 Angularjs 中的子指令传递给 Controller ​​方法

angularjs - Angular 滚动指令

javascript - 使用居中导航栏居中导航栏品牌形象

javascript - 如何使用 Javascript 在 CSS 中隐藏和检索 URL

angularjs - Angular 自定义验证指令。从 View 模型获取错误

javascript - 如何在 AngularJS 中创建类似模型绑定(bind)的字典

javascript - 如何在 ES6 中注入(inject)指令 Controller

javascript - Bootstrap - 日期选择器/禁用数组中的特定日期

javascript - 在 VueJS 中使用按钮水平滚动