小编dan*_*ane的帖子

Angularjs使用ng-model输入[placeholder]指令

因此,第一天使用angularjs工作,我不太了解它.我正在尝试使用angular指令模仿html5占位符.它完全有效,直到我向场中添加ng模型,然后它只在用户与字段交互后才能工作,并且还会破坏字段的任何值.

在这里编码 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();
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

HTML

<textarea ng-model="comment" placehold="with a model it doesn't work"></textarea>
Run Code Online (Sandbox Code Playgroud)

看起来很简单,但我迷路了

javascript angularjs angularjs-directive

10
推荐指数
1
解决办法
2万
查看次数