I有两个指令,它们的功能是在页面加载时选择随机的背景图像。
.directive('carousel', function(){
return{
templateUrl: "../templates/carousel.html",
restrict: "E",
controller: function($scope, $route) {
$scope.imageLevel = 1;
angular.element(document).ready(function() {
var random = Math.floor((Math.random() * 4));
$scope.imageLevel = random;
console.log(random);
});
}
}
})
.directive('stateDisplay', function(){
return {
link: function(scope, el, attrs) {
var parms = attrs['stateDisplay'].split(' ');
var linkVar = parms[0];
var classes = parms.slice(1);
scope.$watch(linkVar, function(newVal) {
el.removeClass(classes.join(' '));
el.addClass(classes[newVal]);
});
}
}
});Carousel.html
<article class="fullheight" state-display="imageLevel image1 image2 image3 image4">
</article> 这些都在一起运行得很好。我想添加一个属性指令来根据滚动位置来偏移图像背景。我有一个属性,但是不确定如何获得css属性的句柄,这个css属性是随机选择并附加到dom的。
这是我到目前为止所知道的:
app.directive('scrollPosition', function($window) {
return {
scope: {
scroll: '=scrollPosition'
},
controller: function($scope) {
$scope.scroll = 0;
},
link: function(scope, element, attrs) {
var windowEl = angular.element($window);
var handler = function() {
scope.scroll = windowEl.scrollTop();
console.log(element[0].attrs);
}
windowEl.on('scroll', scope.$apply.bind(scope, handler));
handler();
}
};
});下面是html:
<article class="fullheight" scroll-position="scroll" state-display="imageLevel image1 image2 image3 image4"> 编译时的HTML:
<carousel class="ng-isolate-scope">
<article scroll-position="scroll" class="fullheight ng-isolate-scope image2" state-display="imageLevel image1 image2 image3 image4">
</artice>
</carousel>我希望获得"image2“css类,或者任意放置在那里的样式,并在处理函数中调整该类css。获得随机选择的类的最佳方法是什么?
console.log(attrs.class);当前仅返回"fullheight“
发布于 2015-03-04 04:19:32
我最终弄明白了:这是最终的代码……
app.directive('scrollPosition', function($window) {
return {
scope: {
scroll: '=scrollPosition'
},
controller: function($scope) {
$scope.scroll = 0;
},
compile: function compile(tElement, tAttrs, transclude) {
return{
post: function(scope, element, attrs) {
var windowEl = angular.element($window);
var lastScrollTop = 0;
var handler = function() {
scope.scroll = windowEl.scrollTop()/5;
var myObject = attrs.$$element[0].classList[2];
console.log(scope.scroll + " " + lastScrollTop);
if(scope.scroll > lastScrollTop){
$('.fullheight.' + myObject).css({backgroundPositionY:"+" + scope.scroll +"px"});
}else{
$('.fullheight.' + myObject).css({backgroundPositionY:"+" + scope.scroll + "px"});
}
lastScrollTop = scope.scroll;
}
windowEl.on('scroll', scope.$apply.bind(scope, handler));
handler();
}
}
}
};
});https://stackoverflow.com/questions/28839433
复制相似问题