获取Angular中可编辑的div值 [英] Get contenteditable div value in angular

查看:213
本文介绍了获取Angular中可编辑的div值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内容可编辑的div,如下所示:

I have a contenteditable div like this:

<div contenteditable="true" ng-model="name">{{ name }}</div>
<input type="button" ng-click="checkScope()" value="Click me">

在我的控制器中:

var app = angular.module('sbAdminApp', []);
app.controller('MyCtrl', function($scope) {
    $scope.name = 'Adrian';

    $scope.checkScope = function(){
        console.log($scope.name);
    }
});

当我单击按钮时,如何使用范围获取contenteditable div的最新值?

How can I get the latest value of contenteditable div using scope when I click the button?

推荐答案

您需要一个指令来进行此操作

you need a directive to work this

app.directive('contenteditable', [function() {
    return {
        require: '?ngModel',
        scope: {

        },
        link: function(scope, element, attrs, ctrl) {
            // view -> model (when div gets blur update the view value of the model)
            element.bind('blur', function() {
                scope.$apply(function() {
                    ctrl.$setViewValue(element.html());
                });
            });

            // model -> view
            ctrl.$render = function() {
                element.html(ctrl.$viewValue);
            };

            // load init value from DOM
            ctrl.$render();

            // remove the attached events to element when destroying the scope
            scope.$on('$destroy', function() {
                element.unbind('blur');
                element.unbind('paste');
                element.unbind('focus');
            });
        }
    };
}]);

您可以像这样使用它

<div contenteditable="true" ng-model="name">{{ name }}</div>

这是演示

这篇关于获取Angular中可编辑的div值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆