单击“添加新按钮”时如何在输入框中闪烁光标?

时间:2015-07-22 07:00:16

标签: angularjs angularjs-directive angularjs-scope

**HTML**

<div ng-app="myApp" ng-controller="myCtrl">
    <input placeholder="Enter your teams name" ng-model="team_input" ng-show="myVar" ng-focus="true" class="team_input"  ng-class="{redPlaceholder : newteamfocus, whitePlaceholder : !newteamfocus}" ng-blur="newteamfocus=true" type="text" name="team_input" autofocus required/>
     <button ng-click="toggleTeamField()">Add New</button>
</div>


**JS**

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.myVar = false;
    $scope.toggleTeamField = function() {
        $scope.myVar = !$scope.myVar;
        $scope.newteamfocus = false;
        $scope.team_input = "";
    };
});

这里我可以显示隐藏的输入框,但是当我点击添加按钮时,闪烁的光标不会出现。如何在输入框中显示闪烁光标。 Plunker

1 个答案:

答案 0 :(得分:2)

您可以使用将元素集中在click上的指令来实现此目的。

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

需要注意的一件重要事情是元素需要在焦点上可见。因此,为0添加超时。

.directive('myFocus', function($timeout) {
  return function(scope, element, attrs) {
    attrs.$observe('myFocus', function() {
      if (scope.$eval(attrs.myFocus)) {
        // Element needs to be visible to focus
        $timeout(function() {
          element[0].focus();
        })
      }
    })
  };
});

//html
<input placeholder="Enter your teams name" my-focus="{{focus}}" ng-model="team_input" ng-show="myVar"  class="team_input"  ng-class="{redPlaceholder : newteamfocus, whitePlaceholder : !newteamfocus}"  type="text" name="team_input" required/>
相关问题