在角度中向{{}}添加占位符

Add a placeholder to {{}} in angular

本文关键字:占位符 添加      更新时间:2023-09-26

我有这个可编辑字段。看起来像这个

<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 : 'Placeholder'}}

{{option.title || 'Placeholder'}}

如果你想添加更复杂的逻辑,你可以创建一个过滤器:

app.filter('placeholder', function() {
  return function(input) {
    return input ? input : 'Placeholder';
  };
});

然后你可以做:

{{option.title | placeholder}}