问题
I have an AngularJS app where I got some data from a webservice and parse some HTML to the template with ng-bind-html ... but when I try to bind data inside the ng-bind-html - nothing happens .. anyone?
I have a little example here,.. not the right case.
HTML
<div ng-controller="MyCtrl">
<div ng-bind-html="post"></div>
</div>
Javascript
angular.module('myApp',[])
.controller('MyCtrl', function($scope, $sce) {
$scope.name = 'World';
$scope.post = $sce.trustAsHtml("<h1>hello {{name}}</h1>");
});
http://jsfiddle.net/bugd67e3/
回答1:
DEMO
Add this directive
angular.module("myApp").directive('compileTemplate', ["$compile", "$parse", function($compile, $parse) {
return {
restrict: 'A',
link: function($scope, element, attr) {
var parse = $parse(attr.ngBindHtml);
function value() { return (parse($scope) || '').toString(); }
$scope.$watch(value, function() {
$compile(element, null, -9999)($scope);
});
}
}
}]);
回答2:
In my case,I have $scope.content
which is dynamic pulled from back-end, with delay of 1-2 seconds. CKEDITOR.inline()
doesn't work if the content is populated after CKEDITOR
is already initialized. I ended up with the following solution, which tackles the 2ways data binding and loading delay well.
<div id="divContent" contenteditable="true" ck-editor ng-model="Content">
</div>
angular.module('ui.ckeditor', []).directive('ckEditor', ["$compile", "$parse", "$sce", function ($compile, $parse, $sce) {
return {
require: '?ngModel',
link: function (scope, elm, attr, ngModel) {
var hasInit = false;
scope.$watch(attr.ngModel, function (newValue, oldValue, scope) {
if (newValue && !hasInit) {
hasInit = true;
var content = $.parseHTML(newValue.toString());
$(elm[0]).append(content);
CKEDITOR.inline(elm[0]);
elm.on('blur keyup change', function () {
scope.$evalAsync(read);
});
}
})
// Write data to the model
function read() {
var html = elm.html();
ngModel.$setViewValue($sce.trustAsHtml(html));
}
}
};
}]);
来源:https://stackoverflow.com/questions/25406461/angularjs-ng-bind-html-2way-data-binding