programing

Controller As 표기법을 사용하여 상위 속성에 액세스하는 방법

iphone6s 2023. 10. 9. 22:22
반응형

Controller As 표기법을 사용하여 상위 속성에 액세스하는 방법

다음과 같이 컨트롤러를 사용하고 있습니다.

<body ng-controller="MainCtrl as main">
   <div ng-controller="ChildCtrl as child">
      {{ main.parentValue }} + {{ child.childValue }}
   </div>
</body>

컨트롤러를 다음과 같이 정의:

app.controller('MainCtrl', function($scope) {
   this.parentValue = 'Main';
});

app.controller('ChildCtrl', function($scope) {
   this.childValue = 'Child';
   // I want to access the property of the parent controller here
});

ChildCtrl은 MainCtrl의 이름 속성을 어떻게 설정할 수 있습니까?여기 플렁커.

$scope 표기법을 사용하면 자식 컨트롤러에서 $scope.parentValue에 액세스할 수 있었습니다.컨트롤러 애즈(Controller As) 표기법을 사용하여 동일한 기능을 구현하는 방법은 무엇입니까?

컨트롤러를 "컨트롤러" 표기법으로 사용하고 있으므로,ChildCtrl당신은 접속할 수 있습니다.MainCtrl사용.$scope.main,예를들면$scope.main.name.

아래의 나의 토막글을 참고하세요.

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

app.controller('MainCtrl', function($scope) {
  this.name = 'Main';
  this.test = {};
});

app.controller('ChildCtrl', function($scope) {
  this.name = 'Child';
  alert($scope.main.name);
});
<html ng-app="app">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-controller="MainCtrl as main">
  <div ng-controller="ChildCtrl as child">
    {{ main.name }} + {{ child.name }}
  </div>
</body>

</html>

"컨트롤러"와 $scope 사용을 혼동해서는 안 됩니다.상위 범위의 데이터를 업데이트하려면 서비스를 사용할 수 있습니다.

예:하위 컨트롤러 내에서 페이지 제목 변경:

app.service("SiteService", function () {
    return {
        title: "Page title";
    }
}


app.controller ("ParentCtrl", function (SiteService) {
    this.site = SiteService;
}

app.controller ("ChildCtrl", function (SiteService) {
    SiteService.title = "New Title";
}

그리고 당신의 템플릿은

<html ng-app="someApp" ng-controller="ParentCtrl as site">
    <head>
         <title>{{site.title}}</title>
    </head>
</html>

이 접근 방식의 주된 장점은 공공 변동과 사유지를 구분하는 것입니다.

데이터 입력하기$scope이게 각진 방법입니다.또한 어느 하나의 컨트롤러에 쉽게 포함할 수 있는 서비스에서 데이터를 설정/가져올 수 있습니다.

이 비디오를 확인하세요: https://egghead.io/lessons/angularjs-sharing-data-between-controllers

언급URL : https://stackoverflow.com/questions/26309323/how-to-access-parent-property-using-controller-as-notation

반응형