在Angular2中重写Jquery下拉函数

时间:2016-02-19 04:42:00

标签: jquery typescript angular

我有一个使用Angular 2打字稿模板插入的Dropdown菜单,但正如我所说的JQueryUI,这个下拉函数在document.ready函数上调用createDropdown()函数,但是由于某些问题,这个没有被调用我无法在HTML中看到下拉列表。所以我需要避免使用jQuery并且需要在Angular2中完全编写代码。下面是我插入的Angular2模板。

import {Component, Input} from 'angular2/core';
import {option} from './option';

@Component({
    selector: 'option-list',
    template: `
        <div class="col-wrap responsive-medium banned-list-container margin-top20">
            <div class="col-4-of-10 padding-bottom10">
                <div class="banned-list-wrap form">
                    <div class="form-field">
                        <label tabindex="1">Groups: </label>
                        <div class="dropdown-wrap"> 
                            <select name="" tabindex="1">
                                <option *ngFor="#option of options; #i=index" value="{{option.value}}" [attr.selected]="i == 0 ? true : null"> 
                                {{option.text}} 
                                </option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-6-of-10 padding-bottom20 padding-left10"> </div>
        </div>
`

})
export class optionlist {
    @Input() options: option[];
}

下面显示了createDropdown()函数(我知道它很冗长)

function createDropdown() {
    var clickEvent;
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        clickEvent = "click";
    } else {
        clickEvent = "click";
    }


    $(".dropdown-wrap").each(function (index, elm) {
        var dropWrap = $(this);

        var dropdownFormatted = $(this).hasClass("loaded");
        var uiMenu = [];
        var selectMenu = [];

        $("select option", dropWrap).each(function (i) {
            selectMenu.push($(this).text());
            uiMenu.push($($(".menu li", dropWrap).get(i)).text());
        });

        var changeOccured = true;
        if (uiMenu.compare(selectMenu) == true && $(".dropdown .label", dropWrap).text() == $("select option:selected", dropWrap).text()) { //if there is any change dynamically occured in <option> or dropdown label  
            changeOccured == false;
        }

        if (changeOccured && $("select", $(this)).length > 0) { //  dropdown button adding for selectable dropdown only 
            if ($(".dropdown", $(this)).length > 0) { //checking if there is already dropdown  button inside
                $(".dropdown", $(this)).attr("rel", $("select option:selected", dropWrap).text());
                $(".dropdown .label", $(this)).text($("select option:selected", dropWrap).text());
            } else {
                var selectedText = $("select option[selected='selected']", $(this)).last().text();
                $(this).append("<button class='dropdown button white' rel='" + selectedText + "'><span class='label'>" + selectedText + "</span><span class='down-arrow'></span></button>");

            }
        }


        if (!dropdownFormatted) { // if it not formatted        
            $(this).addClass("close");
            if ($("select", $(this)).length > 0) {
                if ($(".dropdown.button", $(this)).length > 0) { //removing existing dropdown button
                    $(".dropdown.button", $(this)).remove();
                }
                if ($(".menu", $(this)).length > 0) { //removing existing menu
                    $(".menu", $(this)).remove();
                }


                var tabindex = $("select", $(this)).attr("tabindex");

                var tabindexStr = "";
                if (typeof tabindex !== "undefined") {
                    $("select", $(this)).attr("tabindex", "-1");

                    tabindexStr = "tabindex='" + tabindex + "'";

                }


                var selectedText = $("select option[selected='selected']", $(this)).last().text();
                $(this).append("<button class='dropdown button white' " + tabindexStr + " rel='" + $("select option:selected", dropWrap).text() + "'><span class='label'>" + $("select option:selected", dropWrap).text() + "</span><span class='down-arrow'></span></button>");

                createMenuList(dropWrap);

                $(this).on(clickEvent, ".menu li a", function (event) {
                    // menu list click

                    var thisIndex = $(this).parent().index();

                    $(".dropdown .label", dropWrap).text($(this).text());
                    $(".dropdown", dropWrap).attr("rel", $(dropWrap.find("select option")[thisIndex]).val());


                    $("select option[selected]", dropWrap).removeAttr("selected");
                    selectedOption = $("select option:nth-child(" + (thisIndex + 1) + ")", dropWrap);
                    selectedOption.attr('selected', 'selected');
                    $("select", dropWrap).val(selectedOption.attr("value"));
                    $("select", dropWrap).change();
                    $("select", dropWrap).prop("selectedIndex", thisIndex);
                });

                $("select", $(this)).change(function () {
                    var selectedValue = $("select option[selected]", dropWrap).attr('value');
                    $("select", dropWrap).val(selectedValue);
                    $(".dropdown .label", dropWrap).text($("option:selected", $(this)).text());
                });

                var disableScroll = function (e) {
                    if (e.which == 38 || e.which == 40)
                        return false;
                }

                $(".dropdown.button", $(this)).unbind('focus');
                $(".dropdown.button", $(this)).bind('focus', function (event) {

                    $(document).bind('keydown', disableScroll);
                });

                $(".dropdown.button", $(this)).unbind('blur');
                $(".dropdown.button", $(this)).bind('blur', function (event) {
                    $(document).unbind('keydown', disableScroll);
                });

                $(".dropdown.button", $(this)).unbind('keydown');
                $(".dropdown.button", $(this)).bind('keydown', function (event) {
                    var nextIndex;
                    var selectedIndex;

                    if (event.which == 13) {
                        if (dropWrap.hasClass("open")) {                            
                            $(".menu li.selected a", dropWrap).trigger(clickEvent);
                            $("select", dropWrap).change();
                            return false;
                        }
                    }

                    if (event.which == 38 || event.which == 40) {
                        if (event.which == 40) {
                            selectedIndex = $("select option[selected]", dropWrap).index();
                            if (selectedIndex < $("select option", dropWrap).length - 1)
                                nextIndex = selectedIndex + 1;
                            else
                                nextIndex = 0;
                        }

                        if (event.which == 38) {
                            selectedIndex = $("select option[selected]", dropWrap).index();
                            if (selectedIndex > 0)
                                nextIndex = selectedIndex - 1;
                            else
                                nextIndex = $("select option", dropWrap).length - 1;
                        }

                        if (dropWrap.hasClass('open')) {
                            $(".menu li.selected", dropWrap).removeClass('selected');
                            $($(".menu li", dropWrap).get(nextIndex)).addClass('selected');


                            $("select option[selected]", dropWrap).removeAttr('selected');
                            $($("select option", dropWrap).get(nextIndex)).attr('selected', 'selected');

                            $(".dropdown .label", dropWrap).text($(".menu li.selected", dropWrap).text());
                        }

                        if (dropWrap.hasClass('close')) {
                            createMenuList(dropWrap);
                            dropWrap.removeClass('close').addClass('open');
                        }
                    }


                });
            }


            var clickOutside = function (event) {
                if ($(event.target).parents().index($('.dropdown-wrap.open')) == -1) {
                    collapseDropdown($(".activeMenu"));
                    //alert("clickoutside")
                    $(document).unbind(clickEvent, clickOutside);
                }
            };

            $(this).on(clickEvent, ".menu li a", function () {
                //alert(clickEvent);
                if (!$(this).parent().hasClass("disabled")) {
                    swapClass("close", "open", dropWrap);

                }
            });

            $(this).on("mouseover", ".menu li a", function () {
                dropWrap.addClass("activeMenu");
            });
            $(this).on("mouseout ", ".menu li a", function () {
                dropWrap.removeClass("activeMenu");
            });


            $(".dropdown", $(this)).unbind(clickEvent);

            $(".dropdown", $(this)).bind(clickEvent, function (event) { //make drop down click              
                var offsetLeft = $(this).offset().left;
                var rightSpace = $(window).width() - offsetLeft - $(this).width();

                if (rightSpace < $(".menu", dropWrap).width()) {
                    $(".menu", dropWrap).css({
                        "right": 0,
                        "left": "auto"
                    });
                } else {
                    $(".menu", dropWrap).css({
                        "right": "auto",
                        "left": 0
                    });
                }

                if ($("select", dropWrap).length > 0) {
                    createMenuList(dropWrap);
                }

                collapseDropdown();


                //alert(dropWrap.hasClass("open"));
                if (!dropWrap.hasClass("open")) {
                    setTimeout(function () {
                        $(document).unbind(clickEvent, clickOutside);
                        $(document).bind(clickEvent, clickOutside);
                    }); //on click outside
                }

                swapClass("close", "open", dropWrap);
            });
            if ($("input[type='text']", $(this)).length > 0) {

                $("input[type='text']", $(this)).unbind(clickEvent);
                $("input[type='text']", $(this)).bind(clickEvent, function (event) { //make drop down click 

                    if (!dropWrap.hasClass("open")) {
                        setTimeout(function () {
                            $(document).unbind(clickEvent, clickOutside);
                            $(document).bind(clickEvent, clickOutside);
                        }); //on click outside
                    }
                });
            }
            $(this).addClass("loaded");
        }

    });

}

我的问题是 1.如何避免使用此JQ功能并在HTML中加载我的下拉列表? 要么 2.我在何处以及如何调用此函数来显示下拉列表?

1 个答案:

答案 0 :(得分:1)

为了避免使用jquery函数,你需要在不使用jquery(很多努力)的情况下重写下拉列表实现,或者使用像http://valor-software.com/ng2-bootstrap/这样的第三方下拉库

如果您只想调用createDropdown,假设它在全局范围内,只需在组件上的ngAfterViewInit生命周期事件中调用它

public class ButtonInternetAccess implements View.OnClickListener {

    private String url;
    private Context context;

    public ButtonInternetAccess(Context context, String url) {
        this.context = context;
        this.url = url;
    }

    public void onClick(View v) {

        System.out.println(url);

        Intent callIntent = new Intent(Intent.ACTION_VIEW);
        callIntent.setData(Uri.parse(url));

        try {
            context.startActivity(callIntent);
        } catch (ActivityNotFoundException activityException) {
            Log.e("ONCLICK", "No Activity found", activityException);
        }
    }
}