AngularJS - How do I access the form defined insid

2019-07-03 22:06发布

问题:

I am attempting to access the form inside my directive for validation purposes, so I'd like access to $setPristine, however, I can't seem to figure out how to get the form if it's created using a templateUrl.

I have a plunker detailing the issue here: http://plnkr.co/edit/Sp53xzdTbYxL6DAue1uV?p=preview

I'm getting an error:

Controller 'form', required by directive 'testDirective', can't be found!

Here is the relevant Plunker code:

.js:

var app = angular.module("myApp", []);

app.directive("testDirective", function() {
  return {
    restrict: 'E',
    scope: {},
    templateUrl: "formTemplate.html",
    require: "^form",  // <-- doesn't work
    link: function (scope, element, attrs, ctrl) {
      console.log(ctrl);

      scope.open = function() {
          // Would like to have access to the form here
          // ctrl.$setPristine();
      }
    },
    controller: function($scope) {
      $scope.firstName = "Mark";

      $scope.save = function(form) {
        console.log(form);
      }
    }
  }
})

formTemplate.html:

<form name="testForm" ng-click="save(testForm)">
  <input type="text" ng-model="firstName" />
  <br>
  <input type="submit" value="Save" />
</form>

How can I attach the form in formTemplate.html to the isolated scope of my directive?

回答1:

http://plnkr.co/edit/41hhRPKoIsZ9C8Y9Yi87?p=preview

Try this in your directive:

var form1 = element.find('form').eq(0);
formCtrl = form1.controller('form');
console.log(formCtrl);

this should grab the controller for the form.