无法在加载时获取$scope表单名称



我正在尝试在加载表单时在我的 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
      }
}

发生这种情况是因为 DOM 尚未准备好控制器的构造。您必须改用$onInit回调。来自 AngularJS 文档:

$onInit(( - 在构造元素上的所有控制器并初始化其绑定之后(以及在此元素上的指令的 pre & post 链接函数之前(,在每个控制器上调用。这是放置控制器初始化代码的好地方。

此外,最好使用 require 对象注入ngFormController,而不是将其分配给模型。

这是一个工作示例的小提琴。相关代码为:

.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();
    }
  }
});

最新更新