angularJS可编辑文本区域单击以离开

时间:2015-11-16 13:06:41

标签: javascript angularjs

我有一个角度可编辑的文本字段指令,看起来像这样

myApp.directive('editable', function () {
    return {
        restrict: 'E',
        scope: {
            model: '=',
            placeholder: '@'
        },
        replace: false,
        template: '<span>' +
        '<input type="text" class="form-control" placeholder="Press enter to submit changes" 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:14px;"></i></span>' +
        '</span>',
        link: function (scope, element, attrs) {
            scope.edit = false;
            element.bind('click', function () {
                scope.$apply(scope.edit = true);
                element.find('input').focus();
            });
        }
    };
});

myApp.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind('keypress', function (e) {
            if (e.charCode === 13 || e.keyCode === 13) {
                scope.$apply(attrs.ngEnter);
            }
        });
    };
});

正如您可以看到它当前正在使用ng-enter,它正在应用输入键。

我想要它,这样当你点击元素时,它就像输入键一样。

我尝试添加这个没有用的。

myApp.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind('keypress', function (e) {
            if (e.charCode === 13 || e.keyCode === 13) {
                scope.$apply(attrs.ngEnter);
            }
        });
        element.bind('keypress', function (m) {
            if (m.charCode === 1 || m.keyCode === 1) {
                scope.$apply(attrs.ngEnter);
            }
          });
    };
});

有没有人知道为什么这不起作用

1 个答案:

答案 0 :(得分:0)

您想要blur事件。将第二个keypress绑定替换为以下内容:

element.bind('blur', function (e) {
    scope.$apply(attrs.ngEnter);
});