Get contenteditable div value in angular

帅比萌擦擦* 提交于 2020-07-07 14:12:34

问题


I have a contenteditable div like this:

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

In my controller:

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

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

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


回答1:


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');
            });
        }
    };
}]);

and you can use it like this

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

here is a demo



来源:https://stackoverflow.com/questions/32816942/get-contenteditable-div-value-in-angular

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!