Programing

AngularJ는 컨트롤러 ($ scope)에서 양식 개체에 액세스 할 수 없습니다.

lottogame 2020. 11. 17. 07:39
반응형

AngularJ는 컨트롤러 ($ scope)에서 양식 개체에 액세스 할 수 없습니다.


나는 bootstrap-ui보다 구체적으로 모달 창을 사용하고 있습니다. 그리고 모달에 양식이 있습니다. 원하는 것은 양식 유효성 검사 개체를 인스턴스화하는 것입니다. 그래서 기본적으로 나는 이것을하고 있습니다.

<form name="form">
    <div class="form-group">
        <label for="answer_rows">Answer rows:</label>
        <textarea name="answer_rows" ng-model="question.answer_rows"></textarea>
    </div>
</form>

<pre>
    {{form | json}}
</pre

html 파일에서 양식 객체를 아무 문제없이 볼 수 있지만 컨트롤러에서 양식 유효성 검사 객체에 액세스하려면. 그냥 빈 개체를 출력합니다. 다음은 컨트롤러 예입니다.

.controller('EditQuestionCtrl', function ($scope, $modalInstance) {
    $scope.question = {};
    $scope.form = {};

    $scope.update = function () {
        console.log($scope.form); //empty object
        console.log($scope.question); // can see form input
    };
});

$scope.form컨트롤러에서 액세스 할 수없는 이유는 무엇입니까 ?


을 사용하지 $scope않고 대신 this컨트롤러에서을 사용하는 사용자를 위해 양식 이름 앞에 컨트롤러 별칭을 추가해야합니다. 예를 들면 :

<div ng-controller="ClientsController as clients">
  <form name="clients.something">
  </form>
</div>

그런 다음 컨트롤러에서 :

app.controller('ClientsController', function() {
  // setting $setPristine()
  this.something.$setPristine();
};

또한 전체 답변에 기여하기를 바랍니다.


ng-controller가 양식 요소의 부모 인 경우 일반적인 방법 : 다음 줄을 제거하십시오.

$scope.form = {};

angular가 양식을 컨트롤러로 설정하면 $scope빈 개체로 덮어 씁니다.


OP가 언급했듯이 여기에서는 그렇지 않습니다. 그는을 사용 $modal.open하고 있으므로 컨트롤러는 양식의 부모가 아닙니다. 나는 좋은 해결책을 모른다. 그러나이 문제는 해킹 될 수 있습니다.

<form name="form" ng-init="setFormScope(this)">
...

컨트롤러에서 :

$scope.setFormScope= function(scope){
   this.formScope = scope;
}

나중에 업데이트 기능에서 :

$scope.update = function () {
    console.log(this.formScope.form); 

};

각도 UI 부트 스트랩의 '모달'소스 코드를 보면 지시문이

transclude: true

즉, 모달 창은 지시문 범위의 형제로서 여기에서 부모가 컨트롤러 $ scope 인 새 자식 범위를 만듭니다. 그러면 '양식'은 새로 생성 된 하위 범위에서만 액세스 할 수 있습니다.

한 가지 해결책은 다음과 같이 컨트롤러 범위에서 var를 정의하는 것입니다.

$scope.forms = {};

Then for the form name, we use something like forms.formName1. This way we could still access it from our controller by just call $scope.forms.formName1.

This works because the inheritance mechanism in JS is prototype chain. When child scope tries to create the forms.formName1, it first tries to find the forms object in its own scope which definitely does not have it since it is created on the fly. Then it will try to find it from the parent(up to the prototype chain) and here since we have it defined in the controller scope, it uses this 'forms' object we created to define the variable formName1. As a result we could still use it in our controller to do our stuff like:

if($scope.forms.formName1.$valid){
      //if form is valid
}

More about transclusion, look at the below Misco's video from 45 min. (this is probably the most accurate explanation of what transcluded scopes are that I've ever found !!!)

www.youtube.com/watch?v=WqmeI5fZcho


No need for the ng-init trickery, because the issue is that $scope.form is not set when the controller code is run. Remove the form = {} initialization and get access to the form using a watch:

$scope.$watch('form', function(form) {
  ...
});

I use the documented approach.

https://docs.angularjs.org/guide/forms

so, user the form name, on "save" click for example just pass the formName as a parameter and hey presto form available in save method (where formScopeObject is greated based upon the ng-models specifications you set in your form OR if you are editing this would be the object storing the item being edited i.e. a user account)

<form name="formExample" novalidate>

<!-- some form stuff here -->
Name
<input type="text" name="aField" ng-model="aField" required="" />

<br /><br />

<input type="button" ng-click="Save(formExample,formScopeObject)" />

</form>

To expand on the answer by user1338062: A solution I have used multiple times to initialize something in my controller but had to wait until it was actually available to use:

var myVarWatch = $scope.$watch("myVar", function(){
    if(myVar){
        //do whatever init you need to
        myVarWatch();    //make sure you call this to remove the watch
    }
});

For those using Angular 1.5, my solution was $watching the form on the $postlink stage:

$postLink() {
      this.$scope.$watch(() => this.$scope.form.$valid, () => {
      });
    }

참고URL : https://stackoverflow.com/questions/21574472/angularjs-cant-access-form-object-in-controller-scope

반응형