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

大城市里の小女人 提交于 2019-12-10 20:53:00

问题


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.



来源:https://stackoverflow.com/questions/25771399/angularjs-how-do-i-access-the-form-defined-inside-a-templateurl-in-my-directiv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!