我写了一个 angular.js 指令,它使用 stellar.js 来实现视差效果。当我一个接一个地多次调用同一个指令时,stellar.js 只会在第一个指令上工作。
我阅读了有关 $.stellar('refresh');
的内容,它应该在 DOM 中注入(inject)元素后重新初始化 stellar,但这对我没有影响。在窗口上调用 stellar 也没有任何效果。
这是我的指令代码:
angular.module('ClientApp')
.directive('parallaxModule', function () {
return {
templateUrl: 'views/parallax-module.html',
restrict: 'E',
scope: {
data: '='
},
controller: function() {
$(function(){
$(this).stellar({
horizontalScrolling: false,
verticalScrolling: true,
verticalOffset: 50
});
});
}
};
});
这就是我使用指令的方式:
<parallax-module data="sectionData.para"></parallax-module>
<parallax-module data="sectionData.para"></parallax-module>
这是我的模板:
<div class="parallax-module" data-stellar-background-ratio="0.2">
<div class="wrapper" data-stellar-ratio="2.5">
<div class="title">{{data.title}}</div>
<div class="caption">{{data.caption}}</div>
</div>
</div>
最佳答案
$timeout
起作用是因为应该应用 stellar 插件,而不是应用到每个视差元素,而是应用到滚动容器。在文档中的示例中,它应用于 window
:$(window).stellar();
因此,使用$timeout
,代码“等待”摘要队列的末尾,当它被执行时,所有的指令都被加载。不幸的是,它不必要地为每个指令执行。
解决方案是将指令应用于容器。然后它变得很简单:
.directive("parallaxContainer", function(){
return {
link: function(scope, element){
element.stellar({
horizontalScrolling: false,
verticalScrolling: true,
verticalOffset: 0
});
}
}
})
此解决方案依赖于该容器中的恒星兼容元素(例如,带有 data-stellar-background-ratio
):
<body parallax-container>
<div data-stellar-background-ratio="0.2">
...
</div>
<div data-stellar-background-ratio="0.2">
...
</div>
</body>
编辑:
如果动态加载视差元素,上述代码将无法运行。这使事情有点复杂,但并不多。在这种安排中,我们需要负责触发插件的容器指令,以及实际的视差元素指令,这些指令将自己注册到容器并在加载时通知容器。
element 指令可以使用 ng-include
在内容加载时获得通知。该指令使用 require: "^parallaxContainer"
。
app.directive('parallaxModule', function() {
return {
template: '<div ng-include="\'parallax-module.html\'" onload="notifyLoaded()"></div>',
restrict: 'E',
scope: {
data: '='
},
require: "^parallaxContainer",
link: {
pre: function(scope, element, attrs, parallaxContainer){
parallaxContainer.registerElement();
scope.notifyLoaded = parallaxContainer.notifyElementLoaded;
}
}
};
})
parallaxContainer
指令添加了一个 Controller ,该 Controller 公开了要注册和通知的方法。并在所有子项都已加载时触发插件
app.directive("parallaxContainer", function() {
var parallaxElementCount = 0;
var parallaxElementLoaded = 0;
return {
controller: function($element){
this.registerElement = function(){
parallaxElementCount++;
};
this.notifyElementLoaded = function(){
parallaxElementLoaded++;
if (parallaxElementCount !== 0 && parallaxElementCount === parallaxElementLoaded){
$element.stellar({
horizontalScrolling: false,
verticalScrolling: true,
verticalOffset: 0
});
}
}
},
}
})
请注意,stellar
在多次激活时不起作用(出于某种原因 - 也许在 stellar 文档中有一些关于此的信息),因此一旦触发,加载更多子元素将获胜改变什么。
关于javascript - 使用 stellar.js 的 Angular.js 指令多次使用 - 只有第一个有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28269136/