programing

AngularJS 컨트롤러 및 "엄격 사용"

javajsp 2023. 3. 15. 19:19

AngularJS 컨트롤러 및 "엄격 사용"

최근 JSHint를 사용하기 시작했는데, '엄격하게 사용'이라는 함수 형식을 사용해야 합니다.그때부터 앵글은JS가 다음 오류를 발생시킵니다.

"오류: 'webAddressController' 인수가 함수가 아니므로 정의되지 않았습니다."

"엄격 사용" 기능 형식을 제거하면 컨트롤러 로드는 정상적으로 수행됩니다.

컨트롤러:

(function () {
    "use strict";

    function webAddressController($scope, $rootScope, web_address_service) {
             // Do things
    }

}());

여기서 무슨 일이 일어나고 있는지 아는 사람 있나요?

우선 Pkozlowski는 Angular에서 자신의 일을 잘 알고 있지만, 이것은 사실 Angular의 문제가 아니라 폐쇄의 문제입니다.

Angular는 다음 두 곳에서 컨트롤러를 찾고 있습니다.

  1. Module.controller()를 통해 등록된 컨트롤러의 자체 레지스트리에 있습니다.
  2. 전역 변수(또는 전역 함수 선언)에서

문제는 '엄밀하게 사용'을 위한 폐쇄 내부의 모든 것이 글로벌하지 않다는 것입니다.그것을 포함하는 익명 기능으로 포장되고 사유화됩니다.

(function() {
   // nothing in here is global or even public.
   // "use strict" or not.

   "use strict"; // this is mostly irrelevant.

   // this will not work, because it's wrapped and not global
   function ThisDoesntWork($scope) {
   };

   // window is the global root variable. So this works.
   window.ThisWorks = function($scope) {

   };

   // this will work, because it's explicitly registering the controller
   // presuming app is your Module variable from outside of the closure.
   app.controller('ThisIsBest', function($scope) {

   });

})();

//this works because it's global.
function ThisAlsoWorks($scope) {

}

// if you declare a global var, then set it inside
// of your closure, you're good to go too.
var ThisWillWorkToo;

(function {
    //here we're setting it again.
    ThisWillWorkToo = function($scope) {
    };
})();


// if you're really crazy you can even do this...
 var ThisWillWorkButItsWeird = (function() {
      "use strict";

       function ThisWillWorkButItsWeird($scope) {

       }

       return ThisWillWorkButItsWeird;
  })();

하루의 마지막에, 임의의 기능에 「엄밀하게」를 붙이거나, 필요에 따라서 파일 레벨로 할 수 있습니다.'엄격하게 사용'하는 것 자체가 당신에게는 아무런 문제가 되지 않습니다.보시는 바와 같이 컨트롤러를 등록하는 방법은 수천 가지가 있습니다.권장하는 대로 명시적으로 .controller 메서드를 사용하여 등록하는 것이 가장 좋습니다.

JSHint는 글로벌 변수를 피하기 위한 것이라고 생각합니다(분명히 매우 좋은 관행입니다).

AngularJS는 , 변수에 대해 약간 다른 내 할 수 Angular ).JS는 동일한 문제를 해결하는 데 대해 약간 다른 의견(글로벌 변수 회피)을 가지고 있으며 모듈 내 컨트롤러를 정의할 수 있습니다(글로벌 사용).angular★★★★★★★★★★★★★★★★」모듈을 사용하여 예를 다음과 같이 다시 작성할 수 있습니다.

angular.module('myApp',[]).controller('webAddressController', function($scope) {
    // Do things
});

이를 실제로 보여주는 jsFiddle은 다음과 같습니다.http://jsfiddle.net/t3vBE/1/

이 방법에서는 컨트롤러 컨스트럭터로 글로벌네임스페이스를 오염시키지 않습니다.

하여 JSHint를 허용해야 .angular variable을 합니다.또는 코드 전체를 (모듈을 사용하여) 즉시 실행되는 함수로 랩할 수도 있습니다.

(function () {
    "use strict";

angular.module('myApp',[]).controller('webAddressController', function($scope) {

    $scope.name = 'World';
    // Do things
});

}());​

여기 jsFiddle이 있습니다.http://jsfiddle.net/t3vBE/4/

순수한 JavaScript, "도움말" 함수를 정의해야 하며 그렇지 않으면 Angular에 의존해야 합니다.JS 서비스

@pkzolowski를 실행하는 다른 방법은 각도 모듈이 이미 다른 곳에 로드되어 있는 경우입니다.

var app = angular.module('myApp');
app.controller(...);
app.service(...);
...

여기서의 코멘트에 근거하고 있습니다.angularjs는 다른 파일에서 같은 모듈의 서비스를 정의합니다.

angular.module('myModule', [])을 사용하면 myModule 모듈이 생성되고 myModule이라는 이름의 기존 모듈이 덮어쓰게 됩니다.angular.module('myModule')을 사용하여 기존 모듈을 가져옵니다.

외부와 이전(function)에서 '엄밀하게 사용'을 써본 적이 있습니까?

"use strict"; // <-- add it here
(function () {
    //"use strict"; <-- remove from here

    function webAddressController($scope, $rootScope, web_address_service) {
         // Do things
    }

}());

Yeoman이 생성한 파일을 기반으로 답변합니다.

언급URL : https://stackoverflow.com/questions/12957625/angularjs-controllers-and-use-strict