<!doctype html> <html ng-app="form-example2"> <head> <script src="https://code.angularjs.org/angular-1.0.2.min.js"></script> <script> angular.module('form-example2', []).directive('contenteditable', function() { //自定义指令contenteditable return { require: 'ngModel', link: function(scope, elm, attrs, ctrl) { // view -> model elm.bind('blur', function() { //给元素div绑定blur事件 scope.$apply(function() { ctrl.$setViewValue(elm.html()); //当输入结束后,焦点离开div元素时,就更新model }); }); // model -> view ctrl.$render = function(value) { elm.html(value); //更新视图view }; // load init value from DOM ctrl.$setViewValue(elm.html()); } }; }); </script> </head> <body> <div contentEditable="true" ng-model="content" title="Click to edit">Some</div> <pre>model = {{content}}</pre> <style type="text/css"> div[contentEditable] { cursor: pointer; background-color: #D0D0D0; } </style> </body> </html>
希望你喜欢,并分享我的工作~带你走近AngularJS系列:
在 AngularJS 应用中通过 JSON 文件来设置状态
AngularJS 之 Factory vs Service vs Provider