自适应 AngularJS 指令



这是我们的jQuery代码:

$(document).ready(function(){
    $(window).on("load resize", function(){
        if ($(window).width()<=960){
            $(".myDirective").css("flex-direction", "column")
        }
        else{
            $(".myDirective").css("flex-direction", "row")
        }
    })
});

现在我想创建一个具有相同功能的 AngularJS 指令。我应该怎么做?

我知道如何创建具有特定样式的指令:

.directive('myDirective', function(){
    return{
        link: function(scope, element, attrs){
            element.css({
                flexDirection: 'column'
            });
        }
    }
});

但是如何添加条件呢?

在您的 html 中将此 windowWidth 指令应用于您已将其类设置为 .myDirective 的元素。

Ex. <p class="myDirective" window-width></p>

app.directive('windowWidth', function($window) {
    return {
        restrict: 'A',
        link: function(scope, $element) {
            scope.$watch(function() {
                if($window.width < 960) {
                    $element.css("flex-direction", "column");
                } else {
                    $element.css("flex-direction", "row");
                }
            })
        }, 
    }
});

最新更新