【问题标题】:Reusable Angular directive to set focus on input elements可重用的 Angular 指令将焦点设置在输入元素上
【发布时间】:2014-12-25 05:25:04
【问题描述】:

我是 Angular 的新手,我正在尝试编写一个可重用的指令来将焦点设置在某个父级中的元素上。

<div class="products" ng-controller="productsController" id="products"  >
    Name
    <input type="text"  ng-model="name" tabindex="1" focus-element />
    Price
    <input type="text"  ng-model="price" tabindex="2" focus-element />
</div>

.directive('focusElement', function () {    
    return {
        restrict: 'A',
        link: function($scope, $element, attrs) {
            var fE = function() {
                if ($element[0].value === '') {                    
                    var elms = document.getElementsByTagName('body')[0].getElementsByTagName("input");
                    var alredyFocused = false;
                    for (var i = 0; i < elms.length; i++) {
                        if (elms[i].value === '' && Number(elms[i].getAttribute("tabindex")) < attrs.tabindex) {
                            alredyFocused = true;
                            continue;
                        }
                    }
                    if (!alredyFocused) {
                        $element[0].focus();
                    }
                }
            }

            fE();
            //...some other logic
        }
    }
});

在这段代码中,我正在寻找整个身体内的输入元素,这是错误的。如果我希望指令可重用(div 中的 Id 或 class 或 html 与 div 到 div 不同),如何将指令限制为父 div(控制器)?

我试图为 div 本身编写一个指令,以便将焦点集中在它的第一个没有价值的孩子上,但在这种情况下,我不能使用每个输入元素的 ng-model 来跟踪模型更改(使用$scope.$watch("?ngModule attribute from an input which is many?", function () {}))。

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    为什么不编写一个更简单的指令,它接受一个回调函数并在元素获得焦点时调用它。比如:

    .directive('myDirective', function(){
        return {
            scope: {
                callback: '&'
            },
            link: function (scope, element) {
                element.bind('focus', function() {
                    scope.$apply(scope.callback());
                });
            }
        }
    });
    

    指令不需要知道回调在做什么,只需要在焦点上调用它。这可以应用于所有需要一些焦点行为的元素。

    http://jsfiddle.net/b6ww0rx8/11/

    【讨论】:

    • 谢谢,但我需要将焦点设置在任何空的输入(没有值)上,而不是在元素获得焦点时执行某些操作。抱歉问题解释不清楚,我已经编辑了问题。
    猜你喜欢
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 2011-01-24
    相关资源
    最近更新 更多