15

チェックボックスがクリックされたときに要素にフォーカスを委任するよりクリーンな方法はありますか?これが私がハッキングしたダーティバージョンです:

HTML

<div ng-controller="MyCtrl">
    <input type="checkbox" ng-change="toggled()">
    <input id="name">
</div>

JavaScript

var myApp = angular.module('myApp',[]);

function MyCtrl($scope, $timeout) {
    $scope.value = "Something";
    $scope.toggled = function() {
        console.debug('toggled');
        $timeout(function() {
            $('#name').focus();
        }, 100);
    }
}

JSFiddle: http: //jsfiddle.net/U4jvE/8/

4

4 に答える 4

17

これはどう ?プランカー

 $scope.$watch('isChecked', function(newV){
      newV && $('#name').focus();
    },true);

@asgothと@MarkRajcokは正しいです。ディレクティブを使用する必要があります。私はただ怠け者でした。

これがディレクティブバージョンです。プランカーディレクティブとして作成する理由の1つは、これを再利用できることだと思います。

したがって、HTMLでは、さまざまなモーダルをさまざまなセットに割り当てることができます。

<input type="checkbox" ng-model="isCheckedN">
<input xng-focus='isCheckedN'>


directive('xngFocus', function() {
    return function(scope, element, attrs) {
       scope.$watch(attrs.xngFocus, 
         function (newValue) { 
            newValue && element.focus();
         },true);
      };    
});
于 2012-12-28T23:15:22.250 に答える
7

別のディレクティブの実装 (jQuery を必要としない)、および @maxisam のコードの一部を借用:

myApp.directive('focus', function() {
    return function(scope, element) {
       scope.$watch('focusCheckbox', 
         function (newValue) { 
            newValue && element[0].focus()
         })
    }      
});

HTML:

<input type="checkbox" ng-model="focusCheckbox">
<input ng-model="name" focus>

フィドル

このディレクティブは分離スコープ (または子スコープ) を作成しないため、ディレクティブはスコープにfocusCheckboxプロパティが定義されていると想定します。

于 2012-12-28T23:58:09.573 に答える
5

より興味深いものにし、(変数だけでなく) 式の評価をサポートしたい場合は、次のようにすることができます。

app.directive('autofocusWhen', function ($timeout) {
    return {
        link: function(scope, element, attrs) {
            scope.$watch(attrs.autofocusWhen, function(newValue){
                if ( newValue ) {
                    $timeout(function(){
                        element.focus();
                    });
                }
            });
        }
     };
});

そして、次のように、HTML をもう少し分離することができます。

<input type="checkbox" ng-model="product.selected" />
{{product.description}}
<input type="text" autofocus-when="product.selected" />
于 2014-05-28T19:55:22.113 に答える
0

よりクリーンな方法は、ディレクティブを使用してトグルを実行することです。

app.directive('toggle', function() {
   return {
      restrict: 'A',
      scope: {
         selector: '='
      },
      link: function(scope, element, attrs) {
          element.on('change', function() {
              $(scope.selector).focus();
              scope.$apply();
          });
      }
   }:
});

あなたのhtmlは次のようになります:

<input type='checkbox' toggle selector='#name'>
于 2012-12-28T23:51:01.733 に答える