Javascript 将函数表达式存储在angularjs指令的链接函数中,并通过单击使用它
我有以下angularjs指令,我希望能够使用ng click在property-slider.html中执行showMap()。我错过了什么Javascript 将函数表达式存储在angularjs指令的链接函数中,并通过单击使用它,javascript,angularjs,angularjs-directive,angularjs-scope,flickity,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) { retu
(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单击
之外,您还可以将您的方法保留为指令的“私有”,并检测元素上的事件:
link: function(scope, element, attrs) {
element.on('click', function(e) {
showMap();
});
var showMap = ...
}
谢谢,它可以工作,但如果我将函数表达式设置在$timeout之外,那么在执行时它是未定义的。谢谢c4k提供的信息