AngularJS - 如何访问在我的指令中的 templateUrl 中定义的表单? [英] AngularJS - How do I access the form defined inside a templateUrl in my directive?

查看:21
本文介绍了AngularJS - 如何访问在我的指令中的 templateUrl 中定义的表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问指令中的表单以进行验证,因此我想访问 $setPristine,但是,如果表单是使用 templateUrl 创建的,我似乎无法弄清楚如何获取该表单.

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.

我有一个 plunker 详细说明了这个问题:http://plnkr.co/edit/Sp53xzdTbYxL6DAue1uV?p=预览

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

我收到一个错误:

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

这是相关的Plunker代码:

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:

formTemplate.html:

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

如何将 formTemplate.html 中的表单附加到指令的隔离范围?

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

推荐答案

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.

这篇关于AngularJS - 如何访问在我的指令中的 templateUrl 中定义的表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆