6

我使用带有 ng-repeat 指令的 AngularJS 将对象数组显示为列表。

<li ng-repeat="cue in cues" class="form-inline">
    <input type="text" ng-model="cues[$index].text" class="input-xlarge"/>
    {{cue.isNewest}}
</li>

属性“isNewest”仅在数组的一个元素上为真。我想将键盘焦点设置在该项目的文本输入上。我怎么能用 AngularJS 做到这一点?

4

4 回答 4

24

这是另一个使用 attrs.$observe 的指令实现:

myApp.directive('focus', function () {
  return function (scope, element, attrs) {
    attrs.$observe('focus', function (newValue) {
      newValue === 'true' && element[0].focus();
      // or, if you don't like side effects (see @Christophe's comment):
      //if(newValue === 'true')  element[0].focus();
    });
  }
});

请注意,插入的 DOM 属性值(即{{cue.isNewest}})始终计算为字符串,因此将原因newvalue与字符串'true'而不是关键字进行比较true

HTML:

<input type="text" ng-model="cues[$index].text" focus="{{cue.isNewest}}"
 class="input-xlarge" />{{cue.isNewest}}

这个小提琴也有一个方法来切换数组中的哪个项目应该有焦点。

注意,如果你不加载 jQuery,我们需要element[0].focus()在链接函数中使用(不是element.focus()),因为 jqLit​​e 没有 focus() 方法。

于 2013-01-07T23:27:42.270 回答
4

由于您将操作 DOM,因此您需要创建一个指令。就像是:

var app = angular.module('quirli', []);
app.directive('focusable', function() {
    return {
        restrict: 'A',
        scope: {
            focusable: '@'
        },
        link: function(scope, elm, attrs) {
            scope.$watch('focusable', function (value) {
                if (value) {
                    elm[0].focus();
                }
            });
        }
    };
});

html:

<html ng-app="quirli" lang="en">
....  
<input type="text" ng-model="cues[$index].text" class="input-xlarge" focusable="{{cue.isNewest}}"/>

注:未经测试。

于 2013-01-07T21:54:37.807 回答
1

AngularJS 中没有特殊功能可以接收焦点。您可以在控制器中使用 $watch 来解决此问题,也可以使用指令来解决。

于 2013-01-07T21:44:16.483 回答
1

其他建议的答案对我来说可以工作 9/10 次,但很快我就开始体验“$digest already in progress”的乐趣。

我有 asgoth 和 Mark Rajcok 先前答案的略微修改版本。基本上,您注入 $timeout 依赖项并将 focus() 调用放在 timeout(...) 中。IIRC ng-focus 也是如此。

var app = angular.module('cgeers', []);
app.directive('focus', ["$timeout", function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.focus, function (value) {
                if (value) {
                    $timeout(function() { element[0].focus(); });
                }
            });
        }
    };
}]);
于 2013-12-19T15:15:46.317 回答