我有这个可编辑字段。看起来像这样
<editable model="option.title">{{option.title}}</editable>
我尝试向 {{}}
标签添加占位符。因为目前它只显示用于编辑文本区域的图标。
<editable model="option.title">{{option.title | 'Placeholder here'}}</editable>
这显然是行不通的,有没有添加占位符的方法?
我曾使用过 ng-init
但我只能使用一个,问题是我有多个 {{}} 标签。
这是可编辑指令
App.directive('editable', function() {
return {
restrict: 'E',
scope: {model: '='},
replace: false,
template:
'<span>'+
'<input type="text" class="form-control" ng-model="model" style="width: 100%; font-size: 18px" ng-show="edit" ng-enter="edit=false"></input>'+
'<span ng-show="!edit">{{model}} <i class="fa fa-pencil" style="font-size:20px;"></i></span>'+
'</span>',
link: function(scope, element, attrs) {
scope.edit = false;
element.bind('click', function() {
scope.$apply(scope.edit = true);
element.find('input').focus();
});
}
};
});
最佳答案
Edit2 更简洁的方法是将指令修改为:
app.directive('editable', function() {
return {
restrict: 'E',
scope: { model: '=',
placeholder: '@'},
replace: false,
template:
'<span>'+
'<input type="text" class="form-control" ng-model="model" style="width: 100%; font-size: 18px" ng-show="edit" ng-enter="edit=false"></input>'+
'<span ng-show="!edit">{{model || placeholder}} <i class="fa fa-pencil" style="font-size:20px;"></i></span>'+
'</span>',
link: function(scope, element, attrs) {
scope.edit = false;
element.bind('click', function() {
scope.$apply(scope.edit = true);
element.find('input').focus();
});
}
};
});
然后你可以这样做:
<editable model="option.title" placeholder="This is my placeholder"></editable>
旧
你可以使用:
{{option.title ? option.title : '占位符'}}
或{{option.title || '占位符'}}
如果您想向其中添加更复杂的逻辑,您可以创建一个过滤器:
app.filter('placeholder', function() {
return function(input) {
return input ? input : 'Placeholder';
};
});
然后你可以这样做:
{{option.title | placeholder}}
关于javascript - 以 Angular 向 {{}} 添加占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33386366/