스칼라.js와 Scalajs-angular로 구현한 IsolateForm Scala

앵귤러JS 1.x에서 <form /> 태그를 중첩해서 사용할 경우, 내부 폼의 검증(validation) 상태가 외부 폼에 전이되는 경우가 있다. 일반적으로는 이렇게 폼을 중첩해서 쓸 일이 없겠지만, 만일 어떤 디렉티브가 있고 이 디렉티브에 자체적인 폼과 검증 등이 있다면 <form /> 태그 안에 사용시 의도치 않은 방식으로 동작할 수 있다. 이것을 막기 위해 아래 링크에서 제안하는 것이 IsolateForm 이다.

IsolateForm의 코드는 다음과 같다. 링크된 웹페이지의 답변 가운데 앵귤러 1.5 이상에서 정상 동작하는 코드(CC BY-SA 3.0 라이선스)다.

// 출처 : http://stackoverflow.com/questions/19333544/skip-nested-forms-validation-with-angularjs/37481846#37481846, CC BY-SA 3.0
module.directive('isolateForm', function() {
  return {
    restrict: 'A',
    require: '?form',
    link: function(scope, element, attrs, formController) {
      if (!formController) {
        return;
      }

      var parentForm = formController.$$parentForm; // Note this uses private API
      if (!parentForm) {
        return;
      }

      // Remove this form from parent controller
      parentForm.$removeControl(formController);
    }
  };
});

필자는 Scala.js를 사용하기 때문에, 위 디렉티브를 scalajs-angular 0.8로 재구현했다. 다음과 같다.

import scala.scalajs.js

import org.scalajs.dom.Element

import com.greencatsoft.angularjs._
import com.greencatsoft.angularjs.core.Scope

@injectable("isolateForm")
class IsolateFormDirective extends AttributeDirective with Requires {

  this.requirements += "?form"

  override type ScopeType = NestedScope[Scope]

  override def link(
    scope: NestedScope[Scope],
    elems: Seq[Element],
    attrs: Attributes,
    controllers: Either[Controller[_], js.Any]*) {
    controllers match {
      case Seq(Right(ctrl)) =>
        val parentForm = ctrl.asInstanceOf[js.Dynamic].$$parentForm
        if (!js.isUndefined(parentForm))
          parentForm.$removeControl(ctrl)
      case _ =>
    }
  }
}
Tag :
, , , , , , ,

Leave Comments