我在 Controller 中有一个表单,仅当用户按下指令内的按钮时才加载该表单,事件在该指令上使用 $emit 进行中继。但我的问题是表单在范围内不可用,因此表单的验证始终无效。 这是我的 html,
<directive></directive>
<div class="col-md-12 editForm" ng-if="editMode">
<form name="editPollForm" id="editPollForm" ng-submit="editPoll()" novalidate>
<md-input-container>
<inpu ng-model="payload.a" required>
</md-input-container>
<md-input-container>
<inpu ng-model="payload.b" required>
</md-input-container>
<button type="submit" ng-disabled="editPollForm.$invalid"> Save</button>
</form>
</div>
Controller 功能
$scope.$on('pollEditFormRequested', function(event){
$scope.payload = {};
$scope.payload.a = 'a';
$scope.payload.b = 'b';
$scope.editMode = true;
console.log($scope.editPollForm);
});
$scope.editPoll = function(){
console.log($scope.editPollForm);
//call my submit edit form api
};
在指令生成的 $emit 上被捕获并填充值,一切正常,但提交按钮保持禁用状态,因为 ediPollForm 在每个 console.logs
上输出 undefined
/p>
我做错了什么?我尝试了 $timeout
和 $apply
但无济于事。
最佳答案
表单未定义的原因是因为 ng-if 创建了一个新的子作用域,因此父作用域对新表单一无所知。 为了让它知道您应该将表单包装在父对象中。
$scope.form = {} //with this object the parent will hold a reference to the form
//created in the child scope
$scope.$on('pollEditFormRequested', function(event){
$scope.payload = {};
$scope.payload.a = 'a';
$scope.payload.b = 'b';
$scope.editMode = true;
console.log($scope.form.editPollForm); //here the form will be undefined
//because it's not created yet
});
$scope.editPoll = function(){
console.log($scope.form.editPollForm);
//call my submit edit form api
};
在你的模板中:
<div class="col-md-12 editForm" ng-if="editMode">
<!--new scope here-->
<form name="form.editPollForm" id="editPollForm" ng-submit="editPoll()" novalidate>
<md-input-container>
<inpu ng-model="payload.a" required>
</md-input-container>
<md-input-container>
<inpu ng-model="payload.b" required>
</md-input-container>
<button type="submit" ng-disabled="editPollForm.$invalid"> Save</button>
</form>
</div>
关于javascript - Angular 形式在范围内不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40972200/