prosource

AngularJS는 하위 컨트롤러에서 상위 범위에 액세스합니다.

probook 2023. 2. 27. 22:26
반응형

AngularJS는 하위 컨트롤러에서 상위 범위에 액세스합니다.

컨트롤러를 설정했습니다.data-ng-controller="xyzController as vm"

부모/자녀가 중첩된 컨트롤러가 있는 시나리오가 있습니다.nested html의 부모 속성에 접속하는 데 문제가 없습니다.$parent.vm.property자녀 컨트롤러 내에서 부모 속성에 액세스하는 방법을 알 수 없습니다.

$scope를 주입한 후$scope.$parent.vm.property근데 이게 안 돼요?

조언해 주실 분?

HTML이 다음과 같은 경우 다음과 같은 작업을 수행할 수 있습니다.

<div ng-controller="ParentCtrl">
    <div ng-controller="ChildCtrl">
    </div>
</div>

다음으로 다음과 같이 부모 스코프에 액세스 할 수 있습니다.

function ParentCtrl($scope) {
    $scope.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl($scope) {
    $scope.parentcities = $scope.$parent.cities;
}

뷰에서 부모 컨트롤러에 액세스하려면 다음과 같은 작업을 수행해야 합니다.

<div ng-controller="xyzController as vm">
   {{$parent.property}}
</div>

jsFiddle:http://jsfiddle.net/2r728/을 참조해 주세요.

갱신하다

사실 당신이 정의한 이후부터cities부모 컨트롤러에서 자식 컨트롤러가 모든 범위 변수를 상속합니다.그러니까 이론적으로 전화할 필요가 없어$parent위의 예는 다음과 같이 기술할 수도 있습니다.

function ParentCtrl($scope) {
    $scope.cities = ["NY","Amsterdam","Barcelona"];
}

function ChildCtrl($scope) {
    $scope.parentCities = $scope.cities;
}

앵귤러JS docs는 이 접근방식을 사용합니다.여기서 자세한 내용을 보실 수 있습니다.$scope.

다른 업데이트

이게 원래 포스터에 대한 더 좋은 답변인 것 같아요.

HTML

<div ng-app ng-controller="ParentCtrl as pc">
    <div ng-controller="ChildCtrl as cc">
        <pre>{{cc.parentCities | json}}</pre>
        <pre>{{pc.cities | json}}</pre>
    </div>
</div>

JS

function ParentCtrl() {
    var vm = this;
    vm.cities = ["NY", "Amsterdam", "Barcelona"];
}

function ChildCtrl() {
    var vm = this;
    ParentCtrl.apply(vm, arguments); // Inherit parent control

    vm.parentCities = vm.cities;
}

를 사용하는 경우controller asmethod는 다음과 같이 부모 스코프에 액세스 할 수도 있습니다.

function ChildCtrl($scope) {
    var vm = this;
    vm.parentCities = $scope.pc.cities; // note pc is a reference to the "ParentCtrl as pc"
}

보시는 바와 같이 다양한 방법으로 액세스 할 수 있습니다.$scopes.

업데이트된 바이올린

function ParentCtrl() {
    var vm = this;
    vm.cities = ["NY", "Amsterdam", "Barcelona"];
}
    
function ChildCtrl($scope) {
    var vm = this;
    ParentCtrl.apply(vm, arguments);
    
    vm.parentCitiesByScope = $scope.pc.cities;
    vm.parentCities = vm.cities;
}
    
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script>
<div ng-app ng-controller="ParentCtrl as pc">
  <div ng-controller="ChildCtrl as cc">
    <pre>{{cc.parentCities | json}}</pre>
    <pre>{{cc.parentCitiesByScope | json }}</pre>
    <pre>{{pc.cities | json}}</pre>
  </div>
</div>

방금 확인했습니다.

$scope.$parent.someProperty

잘 먹히네요.

그리고 그것은

{{$parent.someProperty}}

보기 위해서요.

사용하고 있을 때as구문, 예를 들어ParentController as parentCtrl컨트롤러를 정의하고 자녀 컨트롤러의 부모 스코프 변수에 액세스하려면 다음 명령을 사용합니다.

var id = $scope.parentCtrl.id;

어디에parentCtrl를 사용하는 부모 컨트롤러 이름입니다.as구문 및id는 같은 컨트롤러에 정의되어 있는 변수입니다.

자녀 범위 내에서 부모 속성을 직접 업데이트해야 하는 경우가 있습니다.예를 들어 자녀 컨트롤러에 의한 변경 후 부모 제어 날짜와 시간을 저장해야 합니다(예: JSFiddle의 코드).

HTML

<div ng-app>
<div ng-controller="Parent">
    event.date = {{event.date}} <br/>
    event.time = {{event.time}} <br/>
    <div ng-controller="Child">
        event.date = {{event.date}}<br/>
        event.time = {{event.time}}<br/>
        <br>
        event.date: <input ng-model='event.date'><br>
        event.time: <input ng-model='event.time'><br>
    </div>
</div>

JS

    function Parent($scope) {
       $scope.event = {
        date: '2014/01/1',
        time: '10:01 AM'
       }
    }

    function Child($scope) {

    }

범위 상속을 회피하고 "글로벌" 범위에 저장할 수도 있습니다.

애플리케이션에 다른 모든 컨트롤러를 랩하는 메인컨트롤러가 있는 경우 글로벌스코프에 '훅'을 설치할 수 있습니다.

function RootCtrl($scope) {
    $scope.root = $scope;
}

그 후, 임의의 자 컨트롤러로 「글로벌」스코프에 액세스 할 수 있습니다.$scope.root여기서 설정한 내용은 전체적으로 표시됩니다.

예:

function RootCtrl($scope) {
  $scope.root = $scope;
}

function ChildCtrl($scope) {
  $scope.setValue = function() {
    $scope.root.someGlobalVar = 'someVal';
  }
}

function OtherChildCtrl($scope) {
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app ng-controller="RootCtrl">
  
  <p ng-controller="ChildCtrl">
    <button ng-click="setValue()">Set someGlobalVar</button>
  </p>
  
  <p ng-controller="OtherChildCtrl">
    someGlobalVar value: {{someGlobalVar}}
  </p>

</div>

최근에 비슷한 곤란을 겪었던 것 같아요.

function parentCtrl() {
   var pc = this; // pc stands for parent control
   pc.foobar = 'SomeVal';
}

function childCtrl($scope) {

   // now how do I get the parent control 'foobar' variable?
   // I used $scope.$parent

   var parentFoobarVariableValue = $scope.$parent.pc.foobar;

   // that did it
}

설정은 조금 달랐지만, 같은 방법으로 동작할 수 있을 것입니다.

하위 구성 요소에서 'require'를 사용하여 상위 구성 요소의 속성 및 메서드에 액세스할 수 있습니다.다음은 예를 제시하겠습니다.

부모:

.component('myParent', mymodule.MyParentComponent)
...
controllerAs: 'vm',
...
var vm = this;
vm.parentProperty = 'hello from parent';

아이:

require: {
    myParentCtrl: '^myParent'
},
controllerAs: 'vm',
...
var vm = this;
vm.myParentCtrl.parentProperty = 'hello from child';

아마 이것은 재미없을 수도 있지만, 두 가지 모두를 외부 오브젝트로 가리킬 수도 있습니다.

var cities = [];

function ParentCtrl() {
    var vm = this;
    vm.cities = cities;
    vm.cities[0] = 'Oakland';
}

function ChildCtrl($scope) {
    var vm = this;
    vm.cities = cities;
}

여기서의 이점은 ChildCtrl에서 편집한 내용이 부모 데이터에 다시 반영된다는 것입니다.

언급URL : https://stackoverflow.com/questions/21453697/angularjs-access-parent-scope-from-child-controller

반응형