我有一个简单的 ASP.NET MVC 应用程序,其中包含一个 ng-controller。 使用部分 View ,我在该 Controller 中注入(inject)另一个仅在需要时使用的 ng-controller。我怎样才能让它工作,因为我无法正确进行绑定(bind)。这是 plunker带有我需要的简化版本。
<body ng-app="MyApp">
<div id='parent' ng-controller="MyCtrl">
<label>Primitive</label>
<input type="text" ng-model="name">
<label>Object</label>
<input type="text" ng-model="user.name">
<button onclick="addNested();">Add Nested Controller</button>
</div>
</body>
以及 javascript 部分:
var app = angular.module("MyApp", []);
app.controller("MyCtrl", function($scope) {
$scope.name = "ParentName";
$scope.user = {
name: "Peter"
};
});
function addNested() {
$('#parent').append(
'<div class="nested" ng-controller="MyNestedCtrl">'+
'<label>Primitive</label>' +
'<input type="text" ng-model="name"><br />' +
'<label>Primitive with explicit $parent reference</label> <br />' +
'<input type="text" ng-model="$parent.name">' +
'<label>Object</label>' +
'<input type="text" ng-model="user.name">' +
'</div>' +
'<script type="text/javascript">' +
'var a = angular.module("MyApp");' +
'a.controller("MyNestedCtrl", ["$scope", MyNestedCtrl] );' +
'</script>');
}
function MyNestedCtrl($scope)
{
$scope.name = "ChildName";
$scope.user = {
name: "Paul"
};
}
最佳答案
如果您想手动插入 HTML 部分,则必须通知 Angular 您已这样做。具体来说,使用 $compile
服务将 HTML 模板链接到特定范围,从而使绑定(bind)“实时”。最好在指令中而不是在 Controller 中执行此类操作,但出于演示目的,这样做就可以了。
关于javascript - 动态插入嵌套 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26649451/