2017-05-26 46 views
1

我在一個div中呈現HTML文本,然後我可以編輯它。用戶可以修改文本,但有沒有辦法找回在HTML中修改的文本?如何對使用ng-bind-html呈現的可編輯DIV中的文本進行ng模型化?

這是我努力使工作小提琴:

<div ng-controller="MyCtrl"> 
Hello, {{name}}! 
<div class="editable" ng-bind-html="documentBody"></div> 
</div> 

控制器:

var myApp = angular.module('myApp', []); 
     function MyCtrl($scope) { 
      $scope.name = 'Superhero'; 
      $scope.documentBody = '<p align="center"><font size="2">Ciao</font></p><br><p align="center"><font size="2">Bello!</font></p>'; 
      $('.editable').each(function() { 
       this.contentEditable = true; 
      }); 
     } 

http://jsfiddle.net/sirfabio80/5sr8wnzv/

在此先感謝 法比奧

+0

TBH我會問你爲什麼用NG綁定HTML的困擾?爲什麼不寫一個部分html文件,並使用ng-include?然後,您可以像控制器中通常那樣訪問您想要的部分。 – rrd

+0

因爲該html代表我的數據模型中用戶需要編輯的文檔模板的主體... – Micky

回答

1

使用指令像下面。我們不能像你期望的那樣編輯,我們必須以某種簡單的方式使用ng-model。

var myApp = angular.module('myApp',['ngSanitize']); 
 

 
myApp.controller('MyCtrl',function ($scope, $sce) { 
 
    $scope.name = 'Superhero'; 
 
    $scope.names = [{name:"Ciao"},{name:"Bello"},{name:"Allo"}];   
 
}); 
 
myApp.directive('dirNew', function(){ 
 
return { 
 
restrict:"EA", 
 
scope:{repeats:"=",}, 
 
template:'<p align="center" ng-repeat="n in repeats"><span size="2" ng-click="click($index)" ng-hide="n.enabled">{{n.name}}</span><input type="text" ng-show="n.enabled" ng-model="n.name"><button ng-show="n.enabled" ng-click="click($index)">Ok</button></p><br>', 
 
link: function(scope) { 
 
     scope.click = function(index){ 
 
     scope.repeats[index].enabled = !scope.repeats[index].enabled; 
 
     } 
 
    } 
 
} 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-sanitize.js"></script> 
 
<body ng-app="myApp"> 
 
<div ng-controller="MyCtrl">{{names}} 
 
<br> 
 
    Hello, {{name}}!<br> 
 
    Click the text and Edit...... 
 
    <dir-new repeats="names"></dir-new> 
 
</div> 
 
</body>

+0

非常感謝Manikandan! – Micky

+0

歡迎@Micky .. –

相關問題