angular.js - 如何用angularjs写一个<div contenteditable="true">的双向数据绑定的demo

浏览:42日期:2023-01-17

问题描述

如题,想用 <p contenteditable='true'> 做一个简单的文本框,供用户输入。如何在angular中使用,做双向数据绑定?

感谢了!

问题解答

回答1:

<!DOCTYPE html><html> <head><meta charset='utf-8'><style type='text/css'> .container{width:960px; margin:0 auto;}.editor{ margin-right:360px; border:1px outset black; height:300px; padding:30px; } .preview{ padding:30px; float:right;width:300px; border:1px inset grey; height:300px; }</style><script src='http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js'></script> </head> <body><p class=’container’ ng-app='editor'> <p class='preview'>{{content }}</p> <p class=’editor’ contenteditable='true' ng-model='content'></p></p><script type='text/javascript'> var app = angular.module(’editor’, []); app.directive(’contenteditable’, function() { return {require: ’ngModel’,link: function(scope, element, attrs, ctrl) { element.bind(’keyup’, function() { scope.$apply(function() { var html=element.html(); ctrl.$setViewValue(html); }); }); } }; });</script> </body></html>

相关文章: