source

Angular JS: ng-include 및 ng-controller

factcode 2023. 2. 9. 22:49
반응형

Angular JS: ng-include 및 ng-controller

앵귤러로 만들고 있는 앱이 있는데, 8~10개 정도의 뷰가 있습니다.모든 뷰에는 뷰 및 비즈니스 규칙 집합에 따라 공유 바닥글이 있으며, 바닥글에 있는 일부 콘텐츠를 조건부로 표시하거나 숨깁니다.

각 뷰에 대한 컨트롤러와 바닥글에 대한 컨트롤러가 있습니다.ng-include를 사용한 공통 바닥글 레이아웃을 포함합니다.여기서 내가 포함하는html은 ng-controller의 바닥글컨트롤러를 참조합니다.

Index.html

<body ng-controller="MainCtrl as vm">
    <p>Message from Main Controller '{{vm.mainMessage}}'</p>
    <div ng-include="'commonFooter.html'"></div>
</body>

commonFooter.html

<div ng-controller="FooterCtrl as vm">
    <p>Message from Footer Controller '{{vm.message}}'</p>
    <p ng-show="vm.showSomthing">Conditional footer Content</p>
</div>

각 뷰 컨트롤러가 바닥글의 상태와 특정 내용이 숨겨져 있는지 여부를 판단하도록 합니다.(아래 DisplaySomthingInFooter를 표시해야 함)

app.controller('MainCtrl', function($scope) {
  var vm = this;
  vm.mainMessage= 'HEELO';
  vm.shouldDisplaySomthingInFooter = true;
  window.console.log('Main scope id: ' + $scope.$id);
});

그 후 Footer Controller에서 부모 컨트롤러로 돌아가 특정 설정을 꺼내 비즈니스 규칙에 따라 콘텐츠를 활성화/비활성화하려고 했습니다.

app.controller('FooterCtrl', function($scope) {
    var vm = this;
  vm.message = 'vm footer';

  window.console.log('Footer scope id: ' + $scope.$id);
  window.console.log('Footer parent scope id: ' + $scope.$parent.$id);
  window.console.log('Footer grandparent scope id: ' + $scope.$parent.$parent.$id);
  window.console.log('Footer grandparent scope name: ' + $scope.$parent.$parent.mainMessage);
  window.console.log('Footer grandparent scope condition: ' + $scope.$parent.$parent.shouldDisplaySomthingInFooter);

  vm.showSomthing = false; //how to pull from parent scope to bind the ng-show to a value set in the parent from within a ng-include?
});

이 예시는 http://plnkr.co/edit/ucI5Cu4jjPgZNUitY2w0?p=preview 입니다.

여기서 알게 된 것은 콘텐츠를 꺼내기 위해 부모 스코프에 도달했을 때 정의되지 않은 상태로 반환되는 것입니다.그 이유는 잘 모르겠습니다.

scopeid를 체크함으로써 스코프가 조부모 레벨로 네스트 되어 있는 것을 알 수 있습니다.이것은 ng-include가 뷰 스코프 아래에 추가 스코프 레이어를 추가하기 때문이라고 생각합니다. 첨부된 예에서 콘솔에서 out

추가 포인트:$scope 오브젝트를 사용할 필요가 없고 계속 사용할 수 있는 경우var vm = this;바람직한 방법이라고 생각합니다.하지만 거지는 고르는 사람이 될 수 없어:)

app.controller('MainCtrl', function($scope) {
  var vm = this;

잘 부탁드립니다.

외부 컨트롤러의 범위를vm내부 컨트롤러는foo그러면 쉽게 분리하여 내부 컨트롤러 내의 VM을 참조할 수 있습니다.

데모

HTML:

<body ng-controller="MainCtrl as vm">
    <p>Message from Main Controller '{{vm.mainMessage}}'</p>
    <div ng-include="'commonFooter.html'"></div>
</body>

CommonFooter.html:

<div ng-controller="FooterCtrl as footer">
    <p>Message from Footer Controller '{{footer.message}}'</p>
    <p ng-show="vm.shouldDisplaySomethingInFooter">Conditional footer Content</p>
</div>

app.filename:

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

app.controller('MainCtrl', function() {
    var self = this;
    self.mainMessage = 'Hello world';
    self.shouldDisplaySomethingInFooter = true;
});

app.controller('FooterCtrl', function() {
    var self = this;
    self.message = 'vm footer';
});

주의: 사용자 이름을 변경했습니다.var vm = this로.var self = this보기와 컨트롤러 간의 혼동을 줄이고 명확성을 확보합니다.

예상 출력:

조건부로 숨김\timeout 아이템을 나타내는 출력

컨트롤러가 구문(문서 참조)에 사용되는 용도를 잘못 알고 있습니다.이는 특정 컨트롤러를 로컬 스코프에 표시하여 템플릿에서 해당 속성에 액세스할 수 있도록 하는 방법일 뿐입니다.사용할 때someController as vm부모 템플릿과 바닥글 템플릿 모두에서 컨트롤러나 다른 것 간에 연결을 만들지 않습니다.넌 그냥 세팅만 하고 있어vm바닥글의 범위에 속하기 때문에 바닥글 템플릿에서 이 속성을 사용하면 바닥글의 컨트롤러에 액세스하게 됩니다(상위 컨트롤러로의 이동은 차단되어 있습니다).

이 경우 기본적으로 컨트롤러는 구문으로서 전혀 필요하지 않습니다.데이터를 적절히 저장하기만 하면 됩니다.$scope나머지 작업은 스코프 계층이 대신합니다.

부모 컨트롤러:

$scope.features.rock = true;
$scope.features.roll = false;

바닥글 템플릿에서

<p ng-show="features.rock">...</p>
<p ng-show="features.roll">...</p>

해서 '아까', '아까', '아까', '아까', '아까', '아까', '아까', '아까', '아까', '아까', '도 볼 수 있어요.features다른 컨트롤러의 스코프가 부모 컨트롤러의 스코프의 하위이기 때문입니다.

, i i i i i 、 시 i 、 시 changed 。var vm = this;로로 합니다.$scope에서

말은 하지 말 것을 .$scope.$parent당신이 보여준 이유와 정확히 일치해요다음과 같은 다양한 지시사항ng-include,ng-show아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아.

나중에 누군가가 의도적으로든 다른 방법으로든 html을 변경하고 범위를 추가할 경우 사용자는 제어할 수 없습니다.

기능을 .MainCtrl이치노

플런커

$scope.getShouldShow = function() {
    return $scope.shouldDisplaySomthingInFooter;
  };
  $scope.setShouldShow = function(val) {
    $scope.shouldDisplaySomthingInFooter = val;
  };

  $scope.getMainMessage = function () {
    return $scope.mainMessage;
  }

그리고 그들에게 전화하는 것:

<p ng-show="getShouldShow();">Conditional footer Content</p>

그리고:

  window.console.log('Footer grandparent scope name: ' + $scope.getMainMessage());
  window.console.log('Footer grandparent scope condition: ' + $scope.getShouldShow());

언급URL : https://stackoverflow.com/questions/27087730/angularjs-ng-include-and-ng-controller

반응형