Angularjs input[placeholder] 指令与 ng-model 中断 [英] Angularjs input[placeholder] directive breaking with ng-model

查看:45
本文介绍了Angularjs input[placeholder] 指令与 ng-model 中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以第一天开始使用 angularjs,我不太明白.我正在尝试使用 angular 指令模拟 html5 占位符.在我向该字段添加 ng-model 之前,它完全有效,然后它仅在用户与该字段交互并破坏该字段的任何值后才有效.

So first day on the job with angularjs and i'm not quite getting it. I'm trying to mimic an html5 placeholder using an angular directive. It totally works until I add an ng-model to the field and then it only works after a user interacts with the field and also breaks any value the field had.

在这里编码http://jsbin.com/esujax/32/edit

App.directive('placehold', function(){
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var insert = function() {
        element.val(attrs.placehold);
      };

      element.bind('blur', function(){
        if(element.val() === '')
          insert();
      });

      element.bind('focus', function(){
        if(element.val() === attrs.placehold)
          element.val('');
      });

      if(element.val() === '')
        insert();
    }
  }
});

html

<textarea ng-model="comment" placehold="with a model it doesn't work"></textarea>

<小时>

看起来超级简单,但我迷路了


seems super simple but i'm lost

推荐答案

只需对您的示例进行一些修改:

Just few modifications in your sample:

app.directive('placehold', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ctrl) {      

      var value;

      var placehold = function () {
          element.val(attr.placehold)
      };
      var unplacehold = function () {
          element.val('');
      };

      scope.$watch(attr.ngModel, function (val) {
        value = val || '';
      });

      element.bind('focus', function () {
         if(value == '') unplacehold();
      });

      element.bind('blur', function () {
         if (element.val() == '') placehold();
      });

      ctrl.$formatters.unshift(function (val) {
        if (!val) {
          placehold();
          value = '';
          return attr.placehold;
        }
        return val;
      });
    }
  };
});

您可以在这里测试:http://plnkr.co/edit/8m54JO?p=preview

不确定,这是最好的解决方案,无论如何它都有效.即使您在 placehold 属性中输入相同的文本,它也会检查模型的焦点值.

Not sure, that it is the best solution, anyway it works. Even if you type the same text, that you have in your placehold attribute, cause it checks the model's value on focus.

这篇关于Angularjs input[placeholder] 指令与 ng-model 中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆