【发布时间】:2013-11-20 23:08:53
【问题描述】:
我有一个包含多个选项卡的选项卡页面,一旦单击调用服务以返回一些数据。其中一些数据返回 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>
【问题讨论】:
-
为什么要在控制器而不是指令中进行 DOM 修改?
-
这只是举例。实际的 html 通过服务来自服务器。控制器中没有 DOM 操作。我一直想知道是否可以使用指令和 $compile 来编译 html 并将 html 绑定到模型。
-
完全可以使用
$compile(element.contents())(scope),在此之前您可以将字符串添加到element.html()方法并在ngModel上设置$watch,我不知道这是否是您想要的。 ..