IT

Angular UI 모달의 범위 문제

lottoking 2020. 10. 8. 07:28

Angular UI 모달의 범위 문제


각도 UI 모달의 범위를 이해 / 사용하는 데 문제가 있습니다.

(내가 말할 수있는 한) 특히 코드 샘플이 버그를 찾는 곳이 있습니다.

index.html (중요한 부분)

<div class="btn-group">
    <button class="btn dropdown-toggle btn-mini" data-toggle="dropdown">
        Actions
        <span class="caret"></span>
    </button>
    <ul class="dropdown-menu pull-right text-left">
        <li><a ng-click="addSimpleGroup()">Add Simple</a></li>
        <li><a ng-click="open()">Add Custom</a></li>
        <li class="divider"></li>
        <li><a ng-click="doBulkDelete()">Remove Selected</a></li>
    </ul>
</div>

Controller.js (다시 말하지만, 중요한 부분)

MyApp.controller('AppListCtrl', function($scope, $modal){
    $scope.name = 'New Name';
    $scope.groupType = 'New Type';

    $scope.open = function(){
        var modalInstance = $modal.open({
            templateUrl: 'partials/create.html',
            controller: 'AppCreateCtrl'
        });
        modalInstance.result.then(function(response){

            // outputs an object {name: 'Custom Name', groupType: 'Custom Type'}
            // despite the user entering customized values
            console.log('response', response);

            // outputs "New Name", which is fine, makes sense to me.                
            console.log('name', $scope.name);

        });
    };
});

MyApp.controller('AppCreateCtrl', function($scope, $modalInstance){
    $scope.name = 'Custom Name';
    $scope.groupType = 'Custom Type';

    $scope.ok = function(){

        // outputs 'Custom Name' despite user entering "TEST 1"
        console.log('create name', $scope.name);

        // outputs 'Custom Type' despite user entering "TEST 2"
        console.log('create type', $scope.groupType);

        // outputs the $scope for AppCreateCtrl but name and groupType
        // still show as "Custom Name" and "Custom Type"
        // $scope.$id is "007"
        console.log('scope', $scope);

        // outputs what looks like the scope, but in this object the
        // values for name and groupType are "TEST 1" and "TEST 2" as expected.
        // this.$id is set to "009" so this != $scope
        console.log('this', this);

        // based on what modalInstance.result.then() is saying,
        // the values that are in this object are the original $scope ones
        // not the ones the user has just entered in the UI. no data binding?
        $modalInstance.close({
            name: $scope.name,
            groupType: $scope.groupType
        });
    };
});

create.html (전체)

<div class="modal-header">
    <button type="button" class="close" ng-click="cancel()">x</button>
    <h3 id="myModalLabel">Add Template Group</h3>
</div>
<div class="modal-body">
    <form>
        <fieldset>
            <label for="name">Group Name:</label>
            <input type="text" name="name" ng-model="name" />           
            <label for="groupType">Group Type:</label>
            <input type="text" name="groupType" ng-model="groupType" />
        </fieldset>
    </form>
</div>
<div class="modal-footer">
    <button class="btn" ng-click="cancel()">Cancel</button>
    <button class="btn btn-primary" ng-click="ok()">Add</button>
</div>

그래서 내 질문은 : 왜 범위가 UI에 이중 바인딩되지 않습니까? 그리고 왜 this사용자 정의 값이 제공 될 $scope것입니까?

나는 ng-controller="AppCreateCtrl"create.html에서 body div에 추가하려고했지만 "Unknown provider : $ modalInstanceProvider <-$ modalInstance"라는 오류가 발생했습니다.

이 시점에서 내 유일한 옵션 은를 사용하는 대신 this.namethis.groupType을 사용하여 객체를 다시 전달하는 $scope것이지만 잘못된 느낌입니다.


나는 다음과 같이 일하도록 내 것을 얻었다.

var modalInstance = $modal.open({
  templateUrl: 'partials/create.html',
  controller: 'AppCreateCtrl',
  scope: $scope // <-- I added this
});

양식 이름이 없습니다 $parent. AngularUI Bootstrap 버전 0.12.1을 사용하고 있습니다.

나는 이것에 의해이 해결책에 대해 알려졌다 .


중첩 된 범위가 관련된 경우 <input>s를 범위의 멤버에 직접 바인딩하지 마십시오 .

<input ng-model="name" /> <!-- NO -->

최소한 한 단계 더 깊게 바인딩하십시오.

<input ng-model="form.name" /> <!-- YES -->

그 이유는 범위가 프로토 타입 적으로 부모 범위를 상속하기 때문입니다. 따라서 첫 번째 수준 구성원을 설정할 때 부모에 영향을주지 않고 자식 범위에 직접 설정됩니다. 반대로 중첩 된 필드 ( form.name)에 바인딩 할 때 멤버 form는 부모 범위에서 읽히므로 name속성에 액세스하면 올바른 대상에 액세스합니다.

여기에서 자세한 설명을 읽으 십시오 .


2014 년 11 월 업데이트 :

실제로 코드는 ui-bootstrap 0.12.0으로 업그레이드 한 후에 작동합니다. 매개자 범위는 그래서 더 이상 필요한 컨트롤러의 범위와 병합 $parent또는 form.물건.

0.12.0 이전 :

모달은 transclusion을 사용하여 내용을 삽입합니다. 덕분 ngFormname속성 별로 범위를 제어 할 수 있습니다 . 따라서 transcluded 범위를 벗어나려면 다음과 같이 양식을 수정하십시오.

<form name="$parent">

또는

<form name="$parent.myFormData">

모델 데이터는 컨트롤러 범위에서 사용할 수 있습니다.


$scope.open = function () {

          var modalInstance = $uibModal.open({
              animation: $scope.animationsEnabled,
              templateUrl: 'myModalContent.html',
              controller: 'salespersonReportController',
              //size: size
              scope: $scope
            });

      };

그것은 나를 위해 작동합니다 범위 : $ scope 감사합니다 제이슨 Swett


나는 scope : $ scope를 추가하면 작동합니다.

참고 URL : https://stackoverflow.com/questions/18924577/scope-issues-with-angular-ui-modal