programing

컨트롤러가 모듈 내에 있는 경우 AngularJs $scope가 정의되지 않았습니다.

oldcodes 2023. 4. 4. 22:15
반응형

컨트롤러가 모듈 내에 있는 경우 AngularJs $scope가 정의되지 않았습니다.

앵귤러 시드 템플릿을 기본 설정으로 사용하려고 합니다.controllers.js사용하고 있다

angular.module('myApp.controllers', []).
  controller('MyCtrl1', [function($scope) {
      $scope.test = 'scope found!';
  }])
  .controller('MyCtrl2', [function() {

  }]);

그 때$scope항상 정의되어 있지 않습니다.컨트롤러를 모듈에서 꺼내 글로벌하게 등록하면 정상적으로 동작합니다.이하와 같이:

function MyCtrl1($scope) {
    $scope.test = "scope found!";
}
MyCtrl1.$inject = ['$scope'];

왜 그런지 설명해 주실 수 있나요?

그런 거 섞으면 안 돼요.다음 두 가지 방법 중 하나를 선택해야 합니다.

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

// possibility 1 - this is not safe for minification because changing the name
// of $scope will break Angular's dependency injection
app.controller('MyController1', function($scope) {
    // ...
});

// possibility 2 - safe for minification, uses 'sc' as an alias for $scope
app.controller('MyController1', ['$scope', function(sc) {
    // ...
}]);

컨트롤러를 직접 선언하는 다른 구문을 사용하는 것은 권장하지 않습니다.머지않아 앱이 성장함에 따라 유지 및 추적하기가 어려워질 것입니다.단, 필요한 경우 다음 3가지 방법이 있습니다.

function myController1 = function($scope) {
    // not safe for minification
}

function myController2 = ['$scope', function(sc) {
    // safe for minification, you could even rename scope
}]

var myController3 = function(sc) {
    // safe for minification, but might be hard
    // to read if controller code gets longer
}
myController3.$inject = ['$scope'];

올바른 방법은 다음과 같습니다.

angular.module('myApp.controllers', []);

angular.module('myApp.controllers').controller('MyCtrl1', ['$scope', function($scope) {

}]);

저도 그걸 찾고 있었는데, 타이핑이 필요한 것 같아요.'$scope'다음과 같이 기능 전에 수행해야 합니다.

    angular.module('myApp.controllers', []).
  controller('MyCtrl1', ['$scope', function($scope) {
      $scope.test = 'scope found!';
  }])
  .controller('MyCtrl2', ['$scope',function() {

  }]);

말이 되네, 하지만 좀 더 명확해져야 할 것 같은데..

$scope를 사용하고 있는 경우는, 「[]」와 「]」를 간단하게 삭제할 수 있습니다.

angular.module('myApp.controllers', []).
controller('MyCtrl1', function($scope) {
    $scope.test = 'scope found!';
  })
  .controller('MyCtrl2', [
    function() {

    }
  ]);

언급URL : https://stackoverflow.com/questions/16284769/angularjs-scope-undefined-when-controllers-are-inside-a-module

반응형