我正在尝试将a的值存储contenteditable到我的JS代码中。但是我找不到ng-model在这种情况下为什么不起作用的原因。
contenteditable
ng-model
<div ng-app="Demo" ng-controller="main"> <input ng-model="inputValue"></input> <div>{{inputValue}}</div> // Works fine with an input <hr/> <div contenteditable="true" ng-model="contentValue"></div> <div>{{contentValue}}</div> // Doesn't work with a contenteditable </div>
有解决方法吗?
参见: JSFiddle
注意: 我正在创建一个文本编辑器,因此当用户将HTML存储在其后时,用户应该看到结果。(即,用户在存储以下内容时看到:“这是一个 示例 !”This is an <b>example</b> !)
This is an <b>example</b> !
contenteditable标签不能直接与angular的ng模型一起使用,因为contenteditable的方式会在每次更改时重新渲染dom元素。
为此,您必须使用自定义指令包装它:
angular.module('customControl', ['ngSanitize']). directive('contenteditable', ['$sce', function($sce) { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if (!ngModel) return; // do nothing if no ng-model // Specify how UI should be updated ngModel.$render = function() { element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); }; // Listen for change events to enable binding element.on('blur keyup change', function() { scope.$evalAsync(read); }); read(); // initialize // Write data to the model function read() { var html = element.html(); // When we clear the content editable the browser leaves a <br> behind // If strip-br attribute is provided then we strip this out if ( attrs.stripBr && html == '<br>' ) { html = ''; } ngModel.$setViewValue(html); } } }; }]);
<form name="myForm"> <div contenteditable name="myWidget" ng-model="userContent" strip-br="true" required>Change me!</div> <span ng-show="myForm.myWidget.$error.required">Required!</span> <hr> <textarea ng-model="userContent"></textarea> </form>
从原始文档中获取