简体   繁体   中英

Angular.js: How to store div HTML content in scope variable

I have an editable div and I want to store the HTML content in scope variable scope.myText :

<div id="editor" contenteditable="true" ng-model="myText">
    <p>HTML Text</p>
</div>

How can I do that in Angular? Is there any directive to solve this problem? I appreciate any help, thanks.

I found the solution to this problem using ng-blur directive:

Controller:

$scope.updateModel = function(){
    $scope.myText = angular.element(editor).html();
    //if you are using jquery use this line:
    //$scope.myText = $('#editor').html();
};

If you want to initialize the editor content use this:

angular.element(editor).html('<p>initial content</p>'); 
//thanks to @PatrickGrimard

or with jquery:

$('#editor').html('<p>initial content</p>');

View:

<div id="editor" contenteditable="true" data-ng-blur="updateModel()">
    <p>HTML Text</p>
</div>
{{myText}}

为什么不在div中使用textarea,那么你可以在它上面使用ng-model。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM