angularjs实现双击span标签,将span标签变成input标签

本文介绍如何使用Angular结合HTML5的contenteditable属性实现可编辑的内容区域,并通过Angular指令进行双向数据绑定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

借助html5的新特性contenteditable和Angular的指令还是很容易做到

<body ng-app="MyApp">
        <div class="test-container" ng-controller="MyController as vm">
            <div class="test" content-editable ng-model="vm.test"></div>
            <hr/>
            <div class="test" ng-bind="vm.test"></div>
        </div>
    </body>


    (function(){
    angular.module('MyApp', [])
        .controller('MyController', MyController)
        .directive('contentEditable', contentEditable);

    MyController.$inject = [];
    contentEditable.$inject = [];

    function MyController(){
        var vm = this;
        vm.test = 'Hello World!';
    }
    function contentEditable(){
        return {
            require: 'ngModel',
            link: function (scope, element, attrs, ctrl) {
                element.html(scope.vm.test);
                attrs.$set('contenteditable', false);

                ctrl.render = function (value) {
                    element.html(value);
                };

                ctrl.$setViewValue(element.html());

                element.bind('dblclick', function () {
                    if (!attrs.contenteditable) {
                        attrs.$set('contenteditable', true);
                        element[0].focus();
                    }
                });

                element.bind('blur', function () {
                    attrs.$set('contenteditable', false);

                    scope.$apply(function () {
                        ctrl.$setViewValue(element.html());
                    });
                });

                element.bind('keydown', function (event) {
                    var esc_key = event.which === 27,
                        enter_key = event.which === 13;

                    if (esc_key || enter_key) {
                        event.preventDefault();
                        element[0].blur();
                    }
                });
            }
        };
    }
})();


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值