【问题标题】:AngularJS - How do I access the form defined inside a templateUrl in my directive?AngularJS - 如何访问在我的指令中的 templateUrl 中定义的表单?
【发布时间】:2014-09-10 17:20:47
【问题描述】:

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

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

我收到一个错误:

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

这是相关的 Plunker 代码:

.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>

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

【问题讨论】:

    标签: angularjs forms angularjs-directive scope


    【解决方案1】:

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

    在你的指令中试试这个:

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

    这应该获取表单的控制器。

    【讨论】:

    • 效果很好!谢谢!!
    猜你喜欢
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多