所以第一天的工作与
angularjs,我没有得到它.我试图使用角度指令来模拟一个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();
}
}
});
html
<textarea ng-model="comment" placehold="with a model it doesn't work"></textarea>
似乎超简单,但我迷失了
解决方法
您的示例中几个修改:
app.directive('placehold',function() {
return {
restrict: 'A',require: 'ngModel',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属性,因此它会检查模型的焦点值.