programing

심플 앵글범위에 JS 양식이 정의되지 않았습니다.

nicescript 2023. 3. 14. 23:28
반응형

심플 앵글범위에 JS 양식이 정의되지 않았습니다.

앵글이랑 놀기 시작했어JS 폼은 jsfiddle로 되어 있으며, 매우 단순한 폼의 예가 예상대로 동작하지 않는 문제에 이미 직면했습니다.명명된 양식만 있고 어떤 이유로 범위에 표시되지 않습니다(FormController 인스턴스가 필요합니다).

바이올린을 설정했습니다.기본 코드는 다음과 같습니다.

HTML

<div id="mainContainer" ng-app="angularTest" ng-controller="MainCtrl">
    <h1>The Form</h1>
    <form name="theForm">
        <input name="myName" type="text" ng-model="model.name" />
        <input name="submit" type="submit" />
    </form>
</div>

JS

var app = angular.module('angularTest', []);

app.controller('MainCtrl', ['$scope', function($scope) {
    $scope.model = { name: 'Model Name' };
    console.log($scope.theForm); //displays 'undefined'
}]);

jsfiddle에서는 이러한 간단한 예를 많이 찾을 수 없기 때문에 이러한 사이트와 이상한 상호작용을 할 수 있을지 확신이 들지 않았습니다(대부분의 예에서는 정식 컨트롤러를 사용하지 않습니다).플런커도 확인하려고 했는데 같은 문제가 발생했어요.

분명히 뭔가 놓치고 있는 게 분명한데, 여기서 바꾸거나 수정할 게 별로 없네요.아무쪼록 잘 부탁드립니다!

워치를 사용하지 않고 이를 수행하는 좋은 방법은 폼을 등록하는 범위에서 개체를 정의하는 것입니다.

HTML

<div id="mainContainer" ng-app="angularTest" ng-controller="MainCtrl">
    <h1>The Form</h1>
    <form name="form.theForm">
        <input name="myName" type="text" ng-model="model.name" />
        <input type="button" value="Here the scope" ng-click="display()"/>
        <input name="submit" type="submit" />
    </form>
</div>

JS

var app = angular.module('angularTest', []);

app.controller('MainCtrl', ['$scope', function($scope) {
    $scope.model = { name: 'Model Name' };
    $scope.form = {};
    $scope.display = function () {
        console.log($scope.form.theForm);
    }
}]);

폼이 등록되는 것은$scope컨트롤러가 처음 실행된 후 컨트롤러의 상태를 확인합니다.그 때문에,console.log($scope.theForm)모든 것이 올바르게 설정되어 있어도 정의되지 않은 상태로 반환됩니다.

이 예에서는, 다음의 존재에 반응합니다.theForm와치터를 셋업할 수 있습니다.theForm존재에 따라 디버깅텍스트를 설정합니다.

$scope.$watch('theForm', function(theForm) {
    if(theForm) { 
        $scope.formDebugText = 'Form in Scope';
    }
    else {
        $scope.formDebugText = 'Form is Undefined';
    }        
});

이 정보는 http://jsfiddle.net/9k2Jk/1/에서 확인할 수 있습니다.

이 문제를 해결한 것은 부모 오브젝트를 사용하여$scope.

컨트롤러 내:

$scope.forms = {};
$scope.registerUser = function registerUser() {
    if ($scope.forms.userForm.$valid) {
        alert('submit');
    }
};

템플릿:

<form name="forms.userForm" ng-submit="registerUser()">

이유:

사용하시는 경우<form name="userForm"...대신<form name="forms.userForm"...자스코프에 폼을 첨부하지만 $scope는 프로토타입 상속을 사용하기 때문에 원래 $scope에 빈 오브젝트 리터럴을 선언하자마자 폼이 대신 첨부되었습니다.

폼 변수에 액세스하는 권장 방법은 다음과 같습니다.https://docs.angularjs.org/guide/forms - Binding to form and control state

HTML의 경우:

<form name="form">  
<input type="button" ng-click="reset(form)" value="Reset" />
</form>

폼의 이름을 변수로 함수에 전달합니다.

JS의 경우:

$scope.reset = function(form) { 
  alert(form); 
};

변수 'form'을 지금 정의하면 안 됩니다.

저 같은 경우에는ng-include하위 범위를 생성하기 위해 현재 범위 내에서 속성이undefined안전하고 하위 프로그램의 문제를 방지하기 위해 다음과 같은 형식의 이름을 붙이는 데 역변수를 사용해야 합니다.form.theForm.

단, 사전에 컨트롤러에 이 폼명을 선언해 주세요.

<form name="form.theForm">
    <input name="myName" type="text" ng-model="model.name" />
    <input name="submit" type="submit" />
</form>

app.controller('MainCtrl', ['$scope', function($scope) {
    $scope.model = { name: 'Model Name' };
    //You have to declare here, else it will trigger undefined error still.
    $scope.form = {
      theForm: {} 
    };

    $scope.reset = function(){
       $scope.form.theForm.$setPristine();
    }
}]);

$scope에 액세스하기 전에 컨트롤러에서 폼을 다시 초기화할 수 있습니다.이 코드 행으로 작성됩니다.$140입니다.그러면 양식을 사용할 수 있습니다.

angular.element(jQuery('.form-control')).triggerHandler('input')

저는 이 문제에 대한 지침을 작성했습니다.이는 양식에 저장하여 양식이 준비되었을 때 실행할 함수를 전달할 수 있는 속성입니다.

자바스크립트

angular.module('app').directive('formInit', function(){
  return {
    restrict: 'A',
    scope: {
      init: '&formInit'
    },
    controller: function($scope, $element){
      var name = null;
      if ($element[0] && $element[0].name){
        name = $element[0].name;
      }

      var listener = $scope.$watch('init', function(){
        if ($scope[name] && $scope.init){
          $scope.init();
          listener();
        }
      });
    }
  };
});

HTML의 예

<form name="test" form-init="testing()">

서 ★★★★★testing는 컨트롤러 범위의 함수입니다.

언급URL : https://stackoverflow.com/questions/22436501/simple-angularjs-form-is-undefined-in-scope

반응형