html响应中的AngularJs数据绑定

html响应中的AngularJs数据绑定

本文介绍了ajax html响应中的AngularJs数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 python/django 作为具有复杂表单结构的后端.
我有一个角度控制器,它可以制作并请求获得合适的表格.我找到了一个 django-angular 包,它为输入添加了ng-model"属性.所以我在服务器端渲染一个带有表单的模板,并提供一个带有 HTML 的响应.Html 作为响应可能不是最佳实践,但它使事情耗时少了很多.

所以我的问题是我得到了带有表单的 HTML 响应和带有 'ng-model' 属性的输入,但是这个绑定不起作用.有没有办法做到这一点?这里只是这个 html 注入的一个例子:

控制器:

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

模板/视图:

<div ng-bind-html="form"></div>
解决方案

创建指令到 $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

这篇关于ajax html响应中的AngularJs数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 17:55