2017-04-12 112 views
2

我試圖在我的angularjs組件中檢索表單名稱,同時表單正在加載,因爲我想根據解析的某些數據驗證將表單狀態設置爲dirty到組件。我能夠訪問表單名稱,一旦表單完全加載說在一個提交內,但我無法做到這一點上的負載,我怎麼能做到這一點。我正在使用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 
     } 

} 

回答

2

發生這種情況是因爲您的控制器沒有準備好DOM。您必須改用$onInit回撥。從AngularJS docs

$的OnInit() - 調用每個控制器上已建成的所有元素上的控制器之後,並其綁定初始化(與前&交聯功能的指令,此元素之前)。這是放置控制器初始化代碼的好地方。

此外,最好使用require對象注入ngFormController而不是將其分配給您的模型。

這裏是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(); 
    } 
    } 
}); 
+0

嗨萊昂納多,我無法去小提琴。應用程序正在拋出異常,表示無法找到需求「表單」。我相信窗體是我的例子detail.warehouseForm上面的名稱。 –

+0

嘿,小提琴工作正常(http://fiddle.jshell.net/rybkwf25/)。在我提供的示例中,您不需要將'ngFormController'指定給您的模型,因爲您可以「需要」它。 –