我试图在范围内找到一个有角度的形式来验证验证等。
基本案例
我们说我有以下HTML:
<body ng-controller='MyAwesomeController'>
<form name="fooForm">
<textarea ng-model="reason" required=""></textarea>
</form>
<div class='btn btn-primary' ng-click="submit()" ng-class="{'btn-disabled': true}">Awesome Submit Button</div>
</body>
以下控制器
angular.module('MyAwesomeController', '$scope', function(scope){
scope.submit = function(){
console.debug(scope)
}
})
这将有效,经检查后,scope
将包含fooForm
密钥。
现在让我们说我在混合中引入一个角度ui bootstrap模态,如下所示:
破案
<body ng-controller="AwesomeParentController">
<div class="btn btn-primary" ng-click="open()">Open the Modal</div>
</body>
使用以下两个控制器:
.controller('AwesomeParentController', ['$scope', '$modal', function(scope, modal){
scope.open = function(){
options = {
windowClass: 'modal discontinue-modal',
templateUrl: 'modal.html',
controller: 'AwesomeModalController'
}
modalInstance = modal.open(options)
modalInstance.result.then(function(){
console.debug("result!")
})
}
}])
.controller("AwesomeModalController", ['$scope', '$modalInstance', function(scope, modalInstance){
scope.submit = function(){
console.debug(scope)
}
}])
使用以下modal.html:
<form name="fooForm">
<textarea ng-model="reason" required=""></textarea>
</form>
<div class='btn btn-primary' ng-click="submit()">Awesome Submit Button</div>
当点击第一个按钮时,会打开一个模态,第二个按钮点击会打印scope
,其中不包含fooForm
,而是fooForm
位于scope.$$childTail
< / p>
Plunkr:http://embed.plnkr.co/jFGU0teIbL3kUXdyTPxR/preview
可能的修复
<form name="fooForm">
<div ng-controller ="JankyFormController">
<textarea ng-model="reason" required=""></textarea>
<div class='btn btn-primary' ng-click="submit()">Awesome Submit Button</div>
</div>
</form>
.controller('JankyFormController', ['$scope', function(scope){
scope.models['fooForm'] = scope.fooForm
}])
Plunkr:http://embed.plnkr.co/BAZFbS7hFRhHm8DqOpQy/preview
为什么表单被屏蔽了?什么是一个干净的方式来获得它而不必创建嵌套的子控制器?如果我想将ng-class
绑定到表单有效性怎么办?我现在需要围绕($$childTail).fooForm.$valid
构建一块手表吗?
答案 0 :(得分:2)
更新: angular ui-bootstrap 0.12.0解决了问题 - 转换范围与控制器的范围相同,不需要$parent.
。只需升级。
0.12.0之前:
Angular-UI模式使用包含来附加模态内容,这意味着在模式中创建的任何新范围条目都是在子范围内创建的。这种情况发生在form指令中。
这是已知问题:https://github.com/angular-ui/bootstrap/issues/969
我建议使用Angular 1.2.16的快速解决方法:
<form name="$parent.userForm">
userForm
已在模态的控制器$scope
中创建并可用。由于范围继承userForm
访问在标记中保持不变。
<div ng-class="{'has-error': userForm.email.$invalid}"}>