且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ajax html响应中的AngularJs数据绑定

更新时间:2022-10-21 14:49:42

创建指令到 $compile 你的 html.

angular.module("app").directive('compilehtml', ["$compile", "$parse", function($compile, $parse) {返回 {限制:'A',链接:函数($scope,元素,属性){var parse = $parse(attr.ngBindHtml);function value() { return (parse($scope) || '').toString();}$scope.$watch(value, function() {$compile(element, null, -9999)($scope);});}}}]);

然后添加这个指令

演示

I'm using python/django as a backend with complex forms structure.
I got an angular controller which makes and request to get a suitable form. I found a django-angular package that adds 'ng-model' attribute to inputs. So I'm rendering a template with the form on the server side, and provide a response with HTML. Html as a response is probably not best practice, but it makes things a lot less time-consuming.

So my issue is that I get HTML response with form and input with 'ng-model' attributes, but this binding just doesn't work. Is there a way to accomplish that? Here is just a sample of this html injection:

controller:

$scope.form = $sce.trustAsHtml(data.HTML);

template/view:

<div ng-bind-html="form"></div>

Create directive to $compile your html.

angular.module("app").directive('compilehtml', ["$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); 
            });
        }
    }
}]);   

Then add this directive

<div ng-bind-html="form" compilehtml></div>

DEMO