AngularJS ng-bind-html 2way data binding

巧了我就是萌 提交于 2019-12-13 04:06:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!