【问题标题】:HTML attribute to return true based on condition基于条件返回 true 的 HTML 属性
【发布时间】:2017-07-31 22:06:41
【问题描述】:

我在每个重复项目中都有一个带有输入框的 ng-repeat。我已将自动对焦设置为输入。

<input type="text" autofocus />

因此自动对焦将应用于所有项目。但是,iOS 中存在一个错误,即最后一个输入框自动聚焦而不是第一个。

我需要根据条件将其设置为返回 true,如下所示:

<input autofocus="{{$first  ? 'true' : 'false' }}" >

知道如何使用 Angular 来实现这一点吗?

【问题讨论】:

  • $first ? 'true' : 'false' 可以简写为$first;不要使用'true''false' 的字符串表示形式。

标签: javascript angularjs


【解决方案1】:

使用自定义指令来聚焦元素

指令

app.directive('autofocus', ['$timeout', function($timeout) {
  return {
    restrict: 'A',
    link : function(scope, element,attrs) {
       $timeout(function() {
       if(attrs.autofocus==='true'){
        element[0].focus();
       }
      });
    }
  }
}]);

控制器

app.controller('MainCtrl', function($scope) {
  $scope.names = ['first','second','third','fourth','fifth'];
});

HTML

 <div ng-repeat="name in names">
    <input type="text" autofocus="{{$index==0}}" ng-model="name" />
    </div>

Demo plunker link

【讨论】:

  • 似乎无效。尝试更改索引号。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
相关资源
最近更新 更多