javascript - 以 Angular 向 {{}} 添加占位符

标签 javascript angularjs

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

<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/

相关文章:

javascript - HTML5 Javascript : How to Make Sure a Drawn Object Cannot Leave the Canvas

javascript - VUEX,当$store.state为null时怎么办

javascript - 如何使用 Angular UI Router 设置默认 subview

javascript - 在 div 标签中使用 javascript 将 UL 添加到 HTML 时被捕获并出错

javascript - 当一个文件需要全局窗口对象时如何捆绑/构建 JavaScript 文件

javascript - React 构建 block 文件和 list json 中出现意外语法错误

java - 向 DMN 表添加新规则时验证 DMN 规则不重叠

javascript - Angular : sort collection by list of values

html - 如何使工具提示 div 根据屏幕的哪一侧改变一侧? ( Angular )

javascript - 想要在 Angular JS 中将多个 json 对象转换为数组