AngularJS - How do I access the form defined inside templateUrl in my directive?

I am trying to access the form inside my directive for validation purposes, so I would like to access the $ setPristine, however I cannot figure out how to get the form if created with templateUrl.

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

I am getting the error:

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

      

Here is the relevant plunger 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 a form in formTemplate.html to the isolated area of ​​my directive?

+3


source to share


1 answer


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 hijack the controller for the form.

0


source







All Articles