IT story

AngularJS 시드 : JavaScript를 별도의 파일 (app.js, controllers.js, directives.js, filters.js, services.js)에 넣기

hot-time 2020. 8. 30. 19:46
반응형

AngularJS 시드 : JavaScript를 별도의 파일 (app.js, controllers.js, directives.js, filters.js, services.js)에 넣기


내 응용 프로그램을 구성하기 위해 angular-seed 템플릿을 사용하고 있습니다. 처음에는 모든 JavaScript 코드를 단일 파일 인 main.js. 이 파일에는 내 모듈 선언, 컨트롤러, 지시문, 필터 및 서비스가 포함되어 있습니다. 응용 프로그램은 이와 같이 잘 작동하지만 응용 프로그램이 더 복잡 해짐에 따라 확장 성과 유지 관리가 걱정됩니다. angular-seed 템플릿에는 이들 각각에 대해 별도의 파일이 있음을 알았으므로 단일 main.js파일의 코드 를이 질문의 제목에 언급 된 다른 파일 각각 으로 배포하려고 시도 app/js했으며 angular디렉토리 에서 찾았습니다. -씨앗 템플릿.

내 질문은 응용 프로그램이 작동하도록 종속성을 어떻게 관리합니까? 여기에 있는 기존 문서 는 주어진 각 예제가 단일 JavaScript 소스 파일을 보여주기 때문에 이와 관련하여 명확하지 않습니다.

내가 가진 것의 예는 다음과 같습니다.

app.js

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

controllers.js

angular.module('myApp.controllers', []).
    controller('AppCtrl', [function ($scope, $http, $filter, MyService) {

        $scope.myService = MyService; // found in services.js

        // other functions...
    }
]);

filters.js

angular.module('myApp.filters', []).
    filter('myFilter', [function (MyService) {
        return function(value) {
            if (MyService.data) { // test to ensure service is loaded
                for (var i = 0; i < MyService.data.length; i++) {
                    // code to return appropriate value from MyService
                }
            }
        }
    }]
);

services.js

angular.module('myApp.services', []).
    factory('MyService', function($http) {
        var MyService = {};
        $http.get('resources/data.json').success(function(response) {
            MyService.data = response;
        });
        return MyService;
    }
);

main.js

/* This is the single file I want to separate into the others */
var myApp = angular.module('myApp'), []);

myApp.factory('MyService', function($http) {
    // same code as in services.js
}

myApp.filter('myFilter', function(MyService) {
    // same code as in filters.js
}

function AppCtrl ($scope, $http, $filter, MyService) {
    // same code as in app.js
}

종속성을 어떻게 관리합니까?

미리 감사드립니다.


이 문제는 모든 개별 파일에서 응용 프로그램 모듈을 "재 선언"하기 때문에 발생합니다.

앱 모듈 선언 (선언이 올바른 용어인지 확실하지 않음)은 다음과 같습니다.

angular.module('myApp', []).controller( //...

애플리케이션 모듈에 대한 할당 (할당이 올바른 용어인지 확실하지 않음)은 다음과 같습니다.

angular.module('myApp').controller( //...

대괄호가 없음을 확인하십시오.

그래서, 이전 버전, 하나 대괄호 만 일반적으로 한 번 사용되어야한다 app.jsmain.js. 컨트롤러, 지시문, 필터 등 다른 모든 관련 파일 대괄호가 없는 후자의 버전을 사용해야합니다 .

그게 말이 되길 바랍니다. 건배!


응용 프로그램의 다른 부분 ( filters, services, controllers)을 다른 실제 파일에 저장하려면 다음 두 가지를 수행해야합니다.

  1. 더 나은 용어가없는 경우 해당 네임 스페이스를 귀하 app.js또는 각 파일에 선언 하십시오.
  2. 각 파일에서 해당 네임 스페이스를 참조하십시오.

따라서 app.js다음과 같이 보일 것입니다.

angular.module('myApp', ['external-dependency-1', 'myApp.services', 'myApp.controllers'])
.run(function() {
   //...

})
.config(function() {
  //...
});

그리고 각 개별 파일에서 :

services.js

angular.module('myApp.services', []); //instantiates
angular.module('myApp.services') //gets
.factory('MyService', function() { 
  return {};
});

controllers.js

angular.module('myApp.controllers', []); //instantiates
angular.module('myApp.controllers')      //gets
.controller('MyCtrl', function($scope) {
  //snip...
})
.controller('AccountCtrl', function($scope) {
  //snip...
});

이 모든 것을 하나의 호출로 결합 할 수 있습니다.

controllers.js
angular.module('myApp.controllers', []) 
.controller('MyCtrl', function($scope) {
 //snip...
});    

The important part is that you shouldn't redefine angular.module('myApp'); that would cause it to be overwritten when you instantiate your controllers, probably not what you want.


You get the error because you didn't define myApp.services yet. What I did so far is putting all the initial definitions in one file and then use them in another. Like for your example I would put in:

app.js

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

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

That should get rid of the error, though I think you should have a read on the article Eduard Gamonal mentioned in one of the comments.

참고URL : https://stackoverflow.com/questions/16771812/angularjs-seed-putting-javascript-into-separate-files-app-js-controllers-js

반응형