美文网首页
AngularJs中的ng-toggle

AngularJs中的ng-toggle

作者: 木槿惜年2013 | 来源:发表于2017-01-10 22:33 被阅读239次

切换状态在前端开发中很常见,现在流行的网站中好多都用到了toggle。大多数的时候,我们需要实现点击一个元素(一个按钮),使得另一个DOM元素显示和隐藏。根据这种业务需求,我相信有很多种方法来实现。在这篇文章中,我将分享几个用JQuery和AngularJs实现它的技巧。

一、用JQuey实现

HTML:

<body>
    <button>Custom</button>
    <span>From:
        <input type="text" id="from" />
    </span>
    <span>To:
        <input type="text" id="to" />
    </span>
</body>

CSS:

span {
    display: none;
}
.show {
    display: inline-block;
}

JS:

$("button").on("click", function () {
    var state = $(this).data('state');
    state = !state;
    if (state) {
        $("span").addClass("show");
    } else {
        $("span").removeClass("show");
    }
    $(this).data('state', state);
});

当我们来到AngularJs的世界,我们会发现它与JQuery实现非常不同而且有趣。当然,有很多种不同的方法实现它。下面是我用AngularJs实现ng-toggle的小技巧。
二、用AngularJs实现

HTML:

<body ng-app="ngToggle">
    <div ng-controller="AppCtrl">
        <button ng-click="toggleCustom()">Custom</button>
        <span ng-hide="custom">From:
            <input type="text" id="from" />
        </span>
        <span ng-hide="custom">To:
            <input type="text" id="to" />
        </span>
        <span ng-show="custom"></span>
    </div>
</body>

JS:

angular.module('ngToggle', [])
    .controller('AppCtrl',['$scope', function($scope){
        $scope.custom = true;
        $scope.toggleCustom = function() {
            $scope.custom = $scope.custom === false ? true: false;
        };
}]);

原文地址:http://geniuscarrier.com/ng-toggle-in-angularjs/

相关文章

网友评论

      本文标题:AngularJs中的ng-toggle

      本文链接:https://www.haomeiwen.com/subject/vgslbttx.html