将Angularjs动态绑定到新创建的html元素
我有一个标签页,其中有多个选项卡,一旦点击了调用服务来返回一些数据。其中一些数据返回html表单,非常随机。我想收集输入的值,并通过服务将数据发送回服务器。我遇到的问题是我无法从我正在动态创建的html中的输入元素中获取数据。
我创建了一个Plunker来显示问题。请注意,html值可以随时更改,因此html的硬编码将无法正常工作。这里是来自plunker的代码,但请查看plunker,以了解发生的情况。 app.js var app = angular.module('plunker',[]); app.controller('MainCtrl',function($scope,$sce,$compile) { $scope.name = 'World'; $scope.html = ""; $scope.htmlElement = function(){ var html = "<input type='text' ng-model='html'></input>"; return $sce.trustAsHtml(html); } }); 的index.html <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link rel="stylesheet" href="style.css" /> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js"></script> <script src="app.js"></script> </head> <body ng-controller="MainCtrl"> <p>Hello {{name}}!</p> <div ng-bind-html="htmlElement()"></div> {{html}} </body> </html>
一个解决方案是使用ngInclude与$ templateCache,如本
Plunker所示。
有几件事要注意。 首先,您可以使用服务获取模板,并将其添加到$ templateCache,如所描述的here(复制示例): myApp.service('myTemplateService',['$http','$templateCache',function ($http,$templateCache) { $http(/* ... */).then(function (result) { $templateCache.put('my-dynamic-template',result); }); }]); 然后,您可以将其包含在您的模板中,如下所示: <div ng-include="'my-dynamic-template'"></div> ngInclude将允许html字符串上的数据绑定,因此您不需要ngBindHtml。 第二个是,因为ngInclude创建一个新的范围,所以访问新创建的范围之外的html属性将无法正常工作,除非您通过父范围上的对象(例如ng-model =“data.html”)访问它ng-model =“html”。请注意,父范围中的$ scope.data = {}是在这种情况下使html可以在ngInclude范围之外访问的。 (有关为什么您应该始终在ngModels中使用点的更多信息,请参阅this answer)。 编辑 正如您所指出的,当使用服务返回HTML时,ngInclude选项不太有用。 这是编辑的plunker与使用$编译的基于指令的解决方案,如David的评论。 相关补充: app.directive('customHtml',function($compile,$http){ return { link: function(scope,element,attrs) { $http.get('template.html').then(function (result) { element.replaceWith($compile(result.data)(scope)); }); } } }) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |