在模式聚焦时显示信息性消息

时间:2013-11-26 10:29:47

标签: angularjs

      <input type="text" ng-model="user.username" name="username" required>

                <div class="sidetip">
                    <div ng-show="signup.username.$pristine">
                        <span>Choose a Username.</span>
                    </div>

我只想显示“选择用户名”,如果表单是原始的并且输入“用户名”被聚焦。我怎么能做到这一点?

ng-focus看起来我只能应用于输入,而不是我要求的“当输入用户名处于活动状态时,显示这是表单用户名也是原始的”...

2 个答案:

答案 0 :(得分:1)

这样的东西会起作用吗? Here is a demo

<form name='signup' ng-submit="submit()" ng-controller="Ctrl">
    Username:
    <input type="text" ng-model="user.username" name="username" ng-focus="usernameIsFocus=true" ng-blur="usernameIsFocus=false" required />

    <div class="sidetip">
        <div ng-show="signup.username.$pristine && usernameIsFocus">
            <span>Choose a Username. Click outside text field to hide this tip.</span>
        </div>
    </div>
</form>

只是旁注

signup.username.$pristine

不同
user.username == ''

因此,如果您在输入用户名中输入文字然后将其删除,则第一个将是false,第二个将是true

答案 1 :(得分:0)

Angular 1.2具有ngBlur和ngFocus指令,在旧版本中,您可以创建一个指令,该指令在焦点上更改给定变量的值

is-focus="usernameIsFocus"

<input type="text" ng-model="user.username" name="username" required is-focus="usernameIsFocus">
<div class="sidetip">
  <div ng-show="usernameIsFocus">
      <span>Choose a Username.</span>
  </div>
</div>

指令

app.directive('isFocus', function(){
  return {
    scope: {
      isFocus: '='
    },
    link: function(scope, element, attrs){

      element.on('focus', function() {
        scope.$apply(function () {
          scope.isFocus = true;
        });
      });

      element.on('blur', function() {
        scope.$apply(function () {
          scope.isFocus = false;
        });
      });

    }
  };
});

这是一个工作示例: http://plnkr.co/edit/Xan0rO8FKeOAlFC2MwoO?p=preview