Angularjs输入[占位符]指令与NG-模式突破 [英] Angularjs input[placeholder] directive breaking with ng-model
问题描述
与angularjs才行,所以第一天,我不太得到它。我试图模仿使用角指令的HTML5占位符。它完全适用,直到我加一个NG-模型到外地,然后它只能在用户后场相互作用,也打破任何价值的领域了。
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.
code在这里
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=$p $ PVIEW
You can test it here: 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输入[占位符]指令与NG-模式突破的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!