我正在尝试在我的angularjs组件中检索表单名称,同时加载表单,因为我想根据已解析到组件中的一些数据验证将表单状态设置为脏。表单完全加载后我可以在提交内部访问表单名称,但是我无法在加载时执行此操作,我该怎么做。我正在使用ui.router,因此控制器名称是根据状态设置的。
<form class="form-horizontal" name="detail.myForm">
<button ng-click="detail.submit">
</form>
app.component('myDetail', {
bindings: {
alldetails: '<'
},
templateUrl: '/app/detail.html',
controllerAs: 'detail',
controller: function ($state, $transitions, $scope) {
var detail=this;
/*validateData in the alldetails here */
$scope.detail.myForm.$setDirty(); // issue here saying undefined
detail.submit = () =>{
$scope.detail.myForm.$setPristine() //works without any issue
}
}
答案 0 :(得分:2)
由于DOM未在控制器的构造上准备好,因此会发生这种情况。您必须使用$onInit
回调。来自AngularJS docs:
$ onInit() - 在构造了元素上的所有控制器并初始化其绑定之后(在此元素的指令的前置和后置链接函数之前),在每个控制器上调用)。这是为控制器放置初始化代码的好地方。
此外,最好使用ngFormController
对象注入require
,而不是将其分配给模型。
这是一个fiddle with a working example。相关代码是:
.component('myDetail', {
template: '<h1>Details Component</h1>',
controllerAs: 'detail',
// By requiring the form controller, angular will
// create a 'formCtrl' property on your controller with the
// ngFormController instance of the parent form.
require: {
formCtrl: '^form'
},
controller: function() {
// We can't just acces the formController here, couse it will be
// undefined, since the dom isn't ready yet. So we have to use the
// $onInit callback that will be executed by angularjs.
this.$onInit = function() {
/*validateData in the alldetails here */
this.formCtrl.$setDirty();
}
}
});