对类更改的角度操作

时间:2014-12-21 10:29:28

标签: javascript jquery angularjs

我使用jQuery滑块,需要在slideBl元素上检测到cycle-slide-active类,它正在从幻灯片连续移动到幻灯片。

这是我的Jade(html):

#slideshow2(slideshow, data-cycle-speed="500", data-cycle-prev="#prev", data-cycle-next="#next")
div.slideBl(ng-repeat="image in images" ng-init="rating = image.rate" class="slide{{image.id}}")
    span(star-rating, rating-value="rating" max="5" on-rating-selected="rateFunction(rating)")
    img.slide.img-responsive(ng-src="{{image.url}}")
    div() {{image.count}}

我已经阅读过Angular的$ observe和$ watch,感谢Ben Nadel的教程,我最终得到了下一个指令:

.directive('slideBl', function ($compile) {
    return {
        restrict: "C",
        link:
            // I bind the UI events to the local scope.
            function ( $scope, element, attrs ) {

            setTimeout(function () {
                // Register an $observe callback.
                attrs.$observe(
                    "slideBl",
                    function innerObserveFunction() {
                        console.log( "Inner $observe() fired." );
                    }
                );

                // Register a $watch callback.
                $scope.$watch(
                    function innerWatchFunction() {
                        console.log( "Inner $watch() fired." );
                    });
                }, 250);
        }
    };
});

使用此代码,我可以在页面加载后检测所有slideBl元素,但如何继续跟踪cycle-slide-active类更改,以便计算幻灯片显示的次数?

1 个答案:

答案 0 :(得分:2)

您需要观看class属性并检查是否添加了cycle-slide-active类(DEMO):

app.directive('slideBl', function ($compile) {
    return {
        restrict: "C",
        link: function ($scope, element, attrs ) {
            $scope.$watch(function() {
                return element.attr('class');
            }, function(newClasses, oldClasses) {
               if (containsSlideClass(newClasses) && (!containsSlideClass(oldClasses) || newClasses == oldClasses)) {
                   console.log('Slide active');
               }
            });

            function containsSlideClass(classStr) {
                return classStr.split(' ').indexOf('cycle-slide-active') !== -1;
            }
        }
    };
});