1

I have a link when clicked it must show another input and autofocus.

<a ng-click="ctrl.switchAndFocus()" href="#">FOCUS</a>

In controler I have

this.switchAndFocus= function  (){
        if (this.controler.data.radioOne == 'one') {
            this.controler.data.radioTwo = "kmh";
            angular.element("#high").focus();
        }
        else{
            this.controler.data.radioTwo = "kmh";
            angular.element("#low").focus();
        }
    }

(this.controler.data.radioOne is radio button with value 'one', this.controler.data.radioTwo is raduibutton with value 'kmh', angular.element("#high")-> id from input field )

This works, but I have to click on link 2 times. Any idea how to make it work on 1 click to switch and focus ?

1 Answers1

1

https://github.com/hiebj/ng-focus-if

http://plnkr.co/edit/MJS3zRk079Mu72o5A9l6?p=preview

<input focus-if />

(function() {
    'use strict';
    angular
        .module('focus-if', [])
        .directive('focusIf', focusIf);

    function focusIf($timeout) {
        function link($scope, $element, $attrs) {
            var dom = $element[0];
            if ($attrs.focusIf) {
                $scope.$watch($attrs.focusIf, focus);
            } else {
                focus(true);
            }
            function focus(condition) {
                if (condition) {
                    $timeout(function() {
                        dom.focus();
                    }, $scope.$eval($attrs.focusDelay) || 0);
                }
            }
        }
        return {
            restrict: 'A',
            link: link
        };
    }
})();
Jon Hieb
  • 760
  • 8
  • 9