2

テンプレートに入力要素を持つ AngularJS ディレクティブがあります。これで、このディレクティブを<form>タグ内に追加してng-model、問題なくバインドできます。

私が直面している問題は、 に動的に追加される入力が に<form>表示されず、formContoller適切な検証が不可能になることです。

ディレクティブが含まれる<form>に含まれる入力を動的に追加できる独自のスコープを持つディレクティブを含める方法formControllerはありますか?

アップデート

そのため、より単純な例を構築しようとしていたときに、問題の根本的な原因を突き止めました。それが、使用$compileするテンプレートを生成するために使用しているという事実です。plunker で発生する問題の簡略版を作成しました。

http://plnkr.co/edit/XsyZKW?p=preview

AngularJS コード

angular.module('directive', []).directive('containerDir', function() {
  return {
    scope: {
      test: '@'
    },
    compile: function(element, attributes) {
      return function(scope, element, attributes) {
        scope.model = {
          dataObject: {}
        }
      };
    }
  };
});

angular.module('directive').directive('inputDir', function($compile) {
  return {
    template: '<span></span>',
    scope: {
      model: '=dataModel'
    },
    compile: function(element, attributes) {

      return {
        pre: function(scope, element, attributes) {
          var template = '<input type="text" name="username" ng-model="model.username" required />';
          element.html($compile(template)(scope));
        },
        post: function(scope, element, attributes) {
        }
      };
    }
  };
});

テンプレート

<!doctype html>
<html ng-app='directive'>
  <head>
  <script data-require="jquery" data-semver="2.0.1" src="http://code.jquery.com/jquery-2.0.1.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
    <script src="script.js"></script>

  </head>
  <body>
    <div container-dir>
      <form name="testForm" nag-resettable-form style="padding-left: 20px;">
        <div>
          <label for="first-name">First Name</label>
          <input id="first-name"
                 type="text"
                 name="firstName"
                 ng-model="model.dataObject.firstName"
                 required
          />
          <div>value: {{model.dataObject.firstName}}</div>
          <div>{{testForm.firstName.$error | json}}</div>
        </div>
        <div>
          <label for="username">Username</label>
          <span input-dir data-data-model="model.dataObject"></span>
          <div>value: {{model.dataObject.username}}</div>
          <div>{{testForm.username.$error | json}}</div>
        </div>
        <div>
          {{testForm | json}}
        </div>
        <div style="padding-top: 1rem;">
          <button class="primary" ng-click="model.submitForm()">Submit</button>
          <button ng-click="resetForm(formReveal, {}, model.resetForm)">Reset</button>
        </div>
      </form>
    </div>
  </body>
</html>

$compile を使用せずに動作することを示す同じ例を次に示します。

http://plnkr.co/edit/i8Lkt1?p=preview

$compileディレクティブのHTMLを生成するために使用するディレクティブを使用して入力要素を動的に追加することで、私がやろうとしていることが可能かどうかを知りたいです。

問題のディレクティブを使用しないように書き直すことができるかもしれません$compileが、今後の参考のためにこれが可能かどうかを知りたいです。

4

0 に答える 0