Angular,如何在输入上输入运行函数?

时间:2016-07-07 16:12:31

标签: angularjs function

我正试图找出一种在Angular中通过从表单中的输入命中输入来运行函数的好方法。我在stackoverflow帖子上发现了这个:

    public static List<string> GetText(string text, int width)
    {
        string[] palabras = text.Split(' ');
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = new StringBuilder();
        int length = palabras.Length;
        List<string> resultado = new List<string>();
        for (int i = 0; i < length; i++)
        {
            sb1.AppendFormat("{0} ", palabras[i]);
            if (sb1.ToString().Length > width)
            {
                resultado.Add(sb2.ToString());
                sb1 = new StringBuilder();
                sb2 = new StringBuilder();
                sb1.AppendFormat("{0} ", palabras[i]);
            }
            else
            {
                sb2.AppendFormat("{0} ", palabras[i]);
            }
        }
        resultado.Add(sb2.ToString());

        List<string> resultado2 = new List<string>();
        string temp;

        int index1, index2, salto;
        string target;
        int limite = resultado.Count;
        foreach (var item in resultado)
        {
            target = " ";
            temp = item.ToString().Trim();
            index1 = 0; index2 = 0; salto = 2;

            if (limite <= 1)
            {
                resultado2.Add(temp);
                break;
            }
            while (temp.Length <= width)
            {
                if (temp.IndexOf(target, index2) < 0)
                {
                    index1 = 0; index2 = 0;
                    target = target + " ";
                    salto++;
                }
                index1 = temp.IndexOf(target, index2);
                temp = temp.Insert(temp.IndexOf(target, index2), " ");
                index2 = index1 + salto;

            }
            limite--;
            resultado2.Add(temp);
        }
        return resultado2;
    }

但我想知道是否有更好的方法来做到这一点。

2 个答案:

答案 0 :(得分:9)

我使用这样的指令:

.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });
                event.preventDefault();
            }
        });
    };
});

然后,在HTML中你可以这样做:

<input type="text" ng-model"whatever" ng-enter"submitAFunction()">        

答案 1 :(得分:3)

为什么不使用ng-submit?

<form ng-submit="myfunction()">
    <input ng-model="myvalue" type="text">
    <input type="submit" value="submit">
<form>

只要您点击按钮,它就会执行ng-submit上的任何功能,或者按回车键。

https://docs.angularjs.org/api/ng/directive/ngSubmit

您可以在示例中看到您只需按Enter即可。

提交输入也可以是可选的