programing

하나의 컨트롤러를 2개의 다른 뷰에 재사용하는 방법

sourcejob 2023. 3. 20. 23:11
반응형

하나의 컨트롤러를 2개의 다른 뷰에 재사용하는 방법

하나의 컨트롤러를 정의하여 작은 차이로 2개의 뷰에 적용합니다.

각도 코드:

app.controller('MyCtrl', function($scope) {
   $scope.canSave = false;
   $scope.demo = {
      files : [{
         filename: 'aaa.html',
         source: '<div>aaa</div>'
      }, {
         filename: 'bbb.html',
         source: '<div>bbb</div>'
      }]
   }
   $scope.newFile = function(file) {
       $scope.demo.files.push(file);
   }
   $scope.$watch("demo.files", function(val) {
       $scope.canSave = true;
   }, true);
});

표시 1:

<div ng-controller="MyCtrl"></div>

표시 2:

<div ng-controller="MyCtrl"></div>

샘플 코드는 매우 간단하지만, 제 실제 프로젝트에는 많은 코드와 논리가 있습니다.

View 1과 View 2의 기능은 거의 동일하지만 몇 가지 차이만 있을 뿐 컨트롤러에 각 기능에 대한 코드를 작성해야 합니다.

2개의 다른 컨트롤러를 만들고 싶지 않습니다.대부분의 논리가 같기 때문입니다.로직이 서비스가 되는 것은 그다지 일반적이지 않기 때문에 2개의 컨트롤러 간에 로직을 공유하기 위해 서비스로 옮기고 싶지 않습니다.

다른 방법은 없나요?

주어진 조건하에서 저는 아마 이런 걸 하고 있을 거예요.

function MyCommonCtrl(type){
    return function($scope, $http) {
        $scope.x = 5;

        if(type = 't1'){
            $scope.domore = function(){
            }
        }

        ....
        ....
    }
}

angular.module('ng').controller('Type1Ctrl', ['$scope', '$http', MyCommonCtrl('t1')]);
angular.module('ng').controller('Type2Ctrl', ['$scope', '$http', MyCommonCtrl('t2')]);

그리고나서

<div ng-controller="Type1Ctrl"></div>

그리고.

<div ng-controller="Type2Ctrl"></div>

구체적인 설정은 모르지만 두 컨트롤러는 공통 조상으로부터 상속받을 수 있습니다.

Type1Ctrl.prototype = new MyCtrl();
Type1Ctrl.prototype.constructor = Type1Ctrl;

function Type1Ctrl() {
  // constructor stuff goes here
}

Type1Ctrl.prototype.setScope = function() {
  // setScope
};

Type2Ctrl.prototype = new MyCtrl();
Type2Ctrl.prototype.constructor = Type2Ctrl;

function Type2Ctrl() {
  // constructor stuff goes here
}

Type2Ctrl.prototype.setScope = function() {
  // setScope
};

저도 비슷한 문제에 직면했고 범위 상속으로 인해 문제가 해결되었습니다.컨트롤러를 "재사용"하여 공통 상태/모델($scope)과 기능($scope에 연결된 컨트롤러 기능)을 상속하려고 했습니다. "Scope Inheritance 예제"에서 설명한 바와 같이 부모 컨트롤러를 외부 DOM 요소에 연결하고 자녀 컨트롤러를 내부에 연결합니다.부모 컨트롤러의 범위와 기능은 자녀 컨트롤러에 심리스하게 "머지"됩니다.

여기 또 다른 옵션이 있습니다.블로그 투고에서 약간 수정되었습니다.

app.factory('ParentCtrl',function(){
    $scope.parentVar = 'I am from the parent'
  };
});

app.controller('ChildCtrl', function($scope, $injector, ParentCtrl) {
  $injector.invoke(ParentCtrl, this, {$scope: $scope});
});

여기 플런커가 있다

언급URL : https://stackoverflow.com/questions/15618213/how-to-reuse-one-controller-for-2-different-views

반응형