简体   繁体   English

AngularJS - 在控制器中的ng-repeat undefined内形成

[英]AngularJS - form inside ng-repeat undefined in controller

I'm trying to access form object in my controller. 我正在尝试访问控制器中的表单对象。 Form lies inside ng-repeat block it has got its dynamic name and I should be able to access it since v1.3. 表格位于ng-repeat块内,它有动态名称,我应该能够从v1.3开始访问它。

js: JS:

var app = angular.module('app', []);
app.controller('AppCtrl', ['$scope', function($scope) {
  $scope.forms = [0];
  $scope.testForm = function() {
    if($scope.form0 == undefined) {
      $scope.test = 'Form is NOT defined';
    } else {
      $scope.test = 'Form is defined';
    }
  }
}])

html: HTML:

<body ng-app="app">
  <div ng-controller="AppCtrl">
    <div ng-repeat="form in forms" ng-init="formName = 'form' + $index">
      form name should be {{formName}}
      <form name="{{formName}}">
        <input type="text" name="field" />
      </form>
    </div>
  <button ng-click="testForm()">Check if form exists</button>
  <p ng-bind="test"></p>
  </div>
</body>

But in my controller $scope.form0 is undefined - after clicking "Check if form exists" I get "Form is NOT defined" message. 但在我的控制器中,$ scope.form0未定义 - 单击“检查表单是否存在”后,我收到“表单未定义”消息。 Even if I give it a static name ( <form name="form0"> ) I still keep getting undefined. 即使我给它一个静态名称( <form name="form0"> ),我仍然一直未定义。 When I take form out of the ng-repeat loop, it works fine. 当我从ng-repeat循环中取出表格时,它工作正常。

Any idea why it is not set? 知道为什么没有设置?

The example above: https://plnkr.co/edit/Fvy5LdIO0H1vCS9wYR0U?p=preview 上面的示例: https//plnkr.co/edit/Fvy5LdIO0H1vCS9wYR0U?p = preview

Thanks in advance! 提前致谢!

This is because ng-repeat is creating isolated child scopes, the form0 is in the child scope and not visible from the parent (the controller's scope). 这是因为ng-repeat正在创建隔离的子作用域, form0位于子作用域中,而不是从父作用域(控制器的作用域)可见。

So the solution is to pass it to the parent. 因此解决方案是将其传递给父级。 However we cannot do it in ng-init since the form controller is not initialised by that time. 但是我们不能在ng-init中执行它,因为那时表单控制器没有初始化。

One approach I could think of is having a custom directive to bind the formController to a specified scope. 我能想到的一种方法是使用自定义指令将formController绑定到指定的范围。

app.directive("form",function($parse){
  return{
    restrict:"E",
    priority:-1,
    link:function(scope,ele,attrs){
      var targetScope = $parse(attrs.bindToScope)(scope);
      if(targetScope){
        targetScope[attrs.name] = scope[attrs.name];
      }
    }
  }
})

and with this we can tell the form to bind the controller to the scope we specified. 通过这个我们可以告诉表单将​​控制器绑定到我们指定的范围。

<form name="{{formName}}" bind-to-scope='$parent' >
     <input type="text" name="field" />
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM