[英]Insert HTML with AngularJS code inside
关于谁在html字符串中插入带有Angular代码的html的任何帮助。 例:
<div class="container">
<span class='btn' onclick="javascript: clicklink()">click here</span>
<div name="content" id="content">
</div>
</div>
<script>
function clicklink(){
$("#content").html("<span class='label label-danger'>Invoice</span>"+
" <div ng-app ng-init='qty=1;cost=2'> <b>Total:</b> {{qty * cost | currency}} </div>");
}
</script>
如果您正在寻找“ Hello World”之类的示例,那么它可能是最基本的。
也许这个例子没有道理,但是这可能是另一种实现方式。 我有一个使用c#MVC的项目,并且为了渲染某些视图,我使用了ajax
将模式加载到View的Javascript:
function Edit(){
$.ajax({
url: '../Controller_/Action_',
type: 'POST',
datatype: "html",
traditional: true,
data: { data1: data1 },
success: function (result) {
$('._container').html(result);
},
error: function (result) { }
});
}
MVC C#代码:
public ActionResult Edit()
{
...\ code \...
return PartialView("/View/_Edit", model);
}
查看主要:
<a href="#" data-toggle="modal" data-target="#_editModal" onclick="javascript:Edit(1, 'new')">Open Modal</a>
<div name="_container">
<!-- Here load body of modal -->
</div>
在Controller中通过操作(编辑)返回部分视图(编辑)。 应该是一个模态结构:
<div name="_editModal">
@html.LabelFor( x => x.Name)
@html.EditorFor( x => x.Name)
<div ng-app ng-init="qty=1;cost=2">
<b>Invoice:</b>
<div>
Quantity: <input type="number" min="0" ng-model="qty">
</div>
<div>
Costs: <input type="number" min="0" ng-model="cost">
</div>
<div>
<b>Total:</b> {{qty * cost | currency}}
</div>
</div>
</div>
就像一群人在评论和其他答案中已经说过的那样,这绝对是错误的做法。 但是,还有一个内置选项可以使用$compile
使用纯AngularJS解决您的问题。
为了完成这项工作,您需要将所有内容放入controller
或directive
并相应地注入$compile
服务。
您需要使用$compile
服务来生成动态HTML标记的功能,该功能可以使用范围对象作为参数,以生成有效的AngularJS模板。
插入模板后,需要使用$apply
触发AngularJS摘要循环。
<div class="container" ng-controller="MyController">
<span class='btn' ng-click="clicklink()"">click here</span>
<div name="content" id="content">
</div>
</div>
<script>
app.controller("MyController", function($scope, $compile) {
var template = "<button ng-click='doSomething()'>{{label}}</button>";
$scope.clicklink = function(){
$scope.apply(function(){
var content = $compile(template)($scope);
$("#content").append(content);
});
}
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.