Angularjs 为什么$modal为表单引入了一个额外的作用域?
我已经设法使用angular ui引导中的示例演示了这个问题(但您需要打开控制台才能看到它) 为什么表单卡在子作用域而不是$scope中 HTML文件Angularjs 为什么$modal为表单引入了一个额外的作用域?,angularjs,angular-ui-bootstrap,Angularjs,Angular Ui Bootstrap,我已经设法使用angular ui引导中的示例演示了这个问题(但您需要打开控制台才能看到它) 为什么表单卡在子作用域而不是$scope中 HTML文件 <!doctype html> <html ng-app="plunker"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js"></script>
<!doctype html>
<html ng-app="plunker">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
<script src="example.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div ng-controller="ModalDemoCtrl">
<script type="text/ng-template" id="myModalContent.html">
<div class="modal-header">
<h3>I'm a modal!</h3>
</div>
<div class="modal-body">
<ng-form name="myForm">
<ul>
<li ng-repeat="item in items">
<a ng-click="selected.item = item">{{ item }}</a>
</li>
</ul>
Selected: <b>{{ selected.item }}</b>
</ng-form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()">OK</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>
<button class="btn btn-default" ng-click="open()">Open me!</button>
<div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>
</body>
</html>
ng表单不在我期望的$scope中,即使其他$scope项也在那里。表单嵌套范围(由angular添加以进行表单验证)的原因是什么
控制台的输出如下所示:
The form in the $scope says: undefined example.js:37
The form in the $scope.$$childTail says:
Constructor {$error: Object, $name: "myForm", $dirty: false, $pristine: true, $valid: true…}
如果未在
$modal.open
上指定作用域属性,则将使用$rootscope。这是来自文档的
范围-用于模态内容的范围实例(实际上是
$modal服务将创建所提供的
范围)。默认为$rootScope
所以在调用之前设置范围
var modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
scope:$scope,
resolve: {
items: function () {
return $scope.items;
}
}
});
如果要访问主控制器上声明的$scope并使其可供模式访问,则必须包括在模式配置中
scope: $scope
正如Chandermani在上面的回答中所说的那样。这是因为情态动词中使用的转义创造了新的形式范围。我是这样定义表单的:
<form name="$parent.myForm">
然后您可以在模态控制器中使用
$scope.myForm
。您可以在这里查看解决方案,那么注入模态控制器的$scope是什么?这与打开时传递的$scope相同吗?这将是您案例中父控制器的$scope对象ModalDemoCtrl
这不是我要问的问题,我试图理解为什么对话框中有一个额外的作用域,而不是我在其中创建作用域变量的作用域。原来@Khanh TO是对的,答案是在额外的范围内,由模态对话框完成的转置。
<form name="$parent.myForm">