将占位符添加到角度 {{}}

Add a placeholder to angular {{}}

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

我得到了这个可编辑的指令,它工作得很好,除了在模型包含数据之前它不会显示文本。

我尝试过的方法如下:

{{option.title | Test}}

我希望这要么显示option.title,但事实并非如此。

以下是 HTML 代码:

<editable model="option.title">{{option.title | Test}}</editable>

我可以使用ng-if吗?

这是指令:

App.directive('editable', function() {
    return {
        restrict: 'E',
        scope: {model: '='},
        replace: false,
        template:
'<span>'+
    '<input type="text" 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();
            });
        }
    };
});

编辑 1

试试这个:

App.directive('editable', function($compile) {
    return {
        restrict: 'E',
        scope: {model: '='},
        replace: false,
        template:
$compile('<span>'+
    '<input type="text" 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();
            });
        }
    };
});

编辑 2

尝试将变量初始化为:

App.directive('editable', function($compile) {
        return {
            restrict: 'E',
            scope: {model: '='},
            replace: false,
            template:
    $compile('<span>'+
        '<input type="text" 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;
                scope.model = '';
                element.bind('click', function() {
                    scope.$apply(scope.edit = true);
                    element.find('input').focus();
                });
            }
        };
    });

编辑 3

尝试:

<editable ng-init="option={title:''};" model="option.title">{{option.title | Test}}</editable>

如果您不使用 tansclusion,指令的开始标记和结束标记之间的内容将完全替换为指令的模板。

<editable model="option.title">{{option.title || 'Placeholder Text' | Test}}</editable>

-

 {{model || 'text before model updates' | filter}}