How can I set a form contained inside a ng-include to be prestine?

后端 未结 4 1115
轻奢々
轻奢々 2021-01-07 23:33

I have the following code:

4条回答
  •  温柔的废话
    2021-01-07 23:59

    This answer will break all the rules (i.e., DOM traversal inside a controller), but here it is anyway...

    .controller('AdminController', ['$scope','$element',
    function($scope, $element) {
      $scope.$on('$includeContentLoaded', function() {
        var childFormController = $element.find('form').eq(0).controller('form');
        console.log(childFormController);
        childFormController.$setPristine();
      });
    }]);
    

    We wait for the ng-included content to load, then from the $element where AdminController is defined, we look for form elements, pick the first one, then get its FormController.

    Plunker

    If you are only calling $setPristine() as a result of some user interaction, you won't need to look for the $includedContentLoaded event – I only had to do that because I didn't want to create any UI component to trigger the operation, and when the controller first runs, the form doesn't exist yet.

    See also AngularJS: Access formController of a form placed inside transcluded directive from parent controller which deals with the similar problem of trying to access a child from a parent.

    A cleaner solution: define a directive (use it on the ng-include element) and pass it an AdminController function as an attribute. In the directive's link function, call that method and pass the FormController as a parameter. Then the AdminController will have a reference to the desired FormController. (I did not bother coding this up, as I'm not sure you want a solution where you have to use a directive along with ng-include.)

提交回复
热议问题