programing

AngularJS 디렉티브 컨트롤러에는 부모 디렉티브 컨트롤러가 필요합니까?

easyjava 2023. 2. 28. 23:50
반응형

AngularJS 디렉티브 컨트롤러에는 부모 디렉티브 컨트롤러가 필요합니까?

완전히 거꾸로 생각할 수도 있지만, 세 가지 네스트 디렉티브를 작성하려고 합니다.스크린, 컴포넌트, 위젯입니다.위젯이 컴포넌트에서 몇 가지 동작을 트리거할 수 있도록 하고, 그 결과 화면에서 몇 가지 동작을 트리거할 수 있도록 하고 싶습니다.그래서:

.directive('screen', function() {
    return {
        scope: true,
        controller: function() {
            this.doSomethingScreeny = function() {
                alert("screeny!");
            }
        }
    }
})

.directive('component', function() {
    return {
        scope: true,
        controller: function() {
            this.componentFunction = function() {
                WHAT.doSomethingScreeny();
            }
        }
    }
})

.directive('widget', function() {
    return {
        scope: true,
        require: "^component",
        link: function(scope, element, attrs, componentCtrl) {
            scope.widgetIt = function() {
                componentCtrl.componentFunction();
            };
        }
    }
})

<div screen>
    <div component>
        <div widget>
            <button ng-click="widgetIt()">Woo Hoo</button>
        </div>
    </div>
</div>

위젯 링크 fn에 상위 컴포넌트가 필요한 경우require: "^component"컴포넌트 컨트롤러가 포함된 화면에 접근할 수 있도록 하려면 어떻게 해야 합니까?

필요한 것은 WHAT in 컴포넌트이므로 위젯의 버튼을 클릭하면 "screeny!"라고 경고합니다.

감사해요.

문제를 해결할 수 있는 두 가지 방법은 다음과 같습니다.

  1. 사용하고 계시기 때문에scope: true, 모든 스코프가 프로토타입으로 상속됩니다.그래서 만약 당신이 당신의 방법을 정의한다면$scope를 켜는 대신this에서screen컨트롤러, 그 다음 둘 다component그리고.widget기능에 액세스 할 수 있다doSomethingScreeny.
    만지작거리다.
  2. 링크 함수를 정의하다component그리고.require: '^screen'링크 기능에서 screenCtrl을 스코프 속성에 저장하면 디렉티브의 컨트롤러에서 액세스 할 수 있습니다(inject).$scope).
    만지작거리다.

컨트롤러 작성 시 부모 컨트롤러에서 속성 또는 메서드에 직접 액세스하려는 경우 대부분의 작업이 실패합니다.의존성 주입을 사용하여 다른 솔루션을 찾았습니다.$controller서비스.

.directive('screen', function ($controller) {
    return {
       require: '^parent',
       scope: {},
       link: function (scope, element, attr, controller) {
           $controller('MyCtrl', {
                $scope: scope,
                $element: element,
                $attr, attr, 
                controller: controller
           });
       }
    }
})

.controller('MyCtrl, function ($scope, $element, $attr, controller) {});

이 방법은 테스트성이 뛰어나며 원치 않는 컨트롤러로 인해 범위를 오염시키지 않습니다.

return { scope: true } 또는 return { scope: false }은(는) 각 디렉티브의 컨트롤러: functions) {}의 $syslog 변수에는 영향을 주지 않지만 디렉티브 태그는 ng-controller 또는 ng-app 태그에 넣어야 합니다.

JSFiddle

JSFiddle

var myApp = angular.module('myApp', [])

.directive('screen', function() {
  return {
    scope: true,
    controller: function() {
      this.doSomethingScreeny = function() {
        alert("screeny!");
      }
    }
  }
})

.directive('component', function() {
  return {
    scope: true,
    controller: function($element) {
      this.componentFunction = function() {
        $element.controller('screen').doSomethingScreeny();
      }
    }
  }
})

.directive('widget', function() {
  return {
    scope: true,
    controller: function($scope, $element) {
      $scope.widgetFunction = function() {
        $element.controller('component').componentFunction();
      }
    }
  }
})

.controller('MyCtrl', function($scope) {
  $scope.name = 'Superhero';
})
<body ng-app="myApp">

  <div ng-controller="MyCtrl">
    <div screen>
      <div component>
        <div widget>
          <button ng-click="widgetFunction()">Woo Hoo</button>
        </div>
      </div>
    </div>
  </div>

</body>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>

링크 기능이 아닌 컴포넌트 디렉티브컨트롤러에서 화면 디렉티브컨트롤러에 정의되어 있는 기능에 액세스 하려면$element.controller('screen').doSomethingScreeny()(컴포넌트 디렉티브에서).

JSFiddle

각도 문서:

  • controller(name)- 현재 요소 또는 상위 요소의 컨트롤러를 검색합니다.기본적으로는 에 관련되어 있는 컨트롤러를 가져옵니다.ngController지시.한다면name는 camelCase 디렉티브명으로 제공되며, 이 디렉티브의 컨트롤러가 취득됩니다(예:'ngModel').

언급URL : https://stackoverflow.com/questions/15622863/angularjs-directive-controllers-requiring-parent-directive-controllers

반응형