Angular Directives用于改变属性的通信

时间:2015-03-03 18:37:02

标签: angularjs angularjs-directive

我有两个指令,用于在pageload上选择随机背景图像。

.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> 

这些功能很好。我想添加一个属性指令,以根据滚动位置偏移图像背景。我有一个属性,但不知道如何获得随机选择并附加到dom的css属性的句柄。

这是我到目前为止所做的:

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>

我想抓住&#34; image2&#34; css类,或随机放置的任何样式,并在处理函数中调整类css。什么是获得随机选择的类的最佳方法?

console.log(attrs.class);

目前只返回&#34; fullheight&#34;

1 个答案:

答案 0 :(得分:0)

我最终搞清楚了:这是最终的代码......

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


}
  };
});