Angular.js 컨트롤러 매개 변수 이해
저는 방금 Angular.js를 배우기 시작 했고 Angular 홈페이지의 "Wire up a Backend"예제에서 project.js 를 살펴 보았습니다 .
컨트롤러 기능의 매개 변수에 대해 혼란 스럽습니다.
function ListCtrl($scope, Projects) {
...
}
function CreateCtrl($scope, $location, $timeout, Projects) {
...
}
function EditCtrl($scope, $location, $routeParams, angularFire, fbURL) {
angularFire(fbURL + $routeParams.projectId, $scope, 'remote', {}).
then(function() {
...
});
}
이러한 컨트롤러 함수는 routeProvider에서 호출되지만 매개 변수가 제공되지 않습니다.
$routeProvider.
when('/', {controller:ListCtrl, templateUrl:'list.html'}).
when('/edit/:projectId', {controller:EditCtrl, templateUrl:'detail.html'}).
when('/new', {controller:CreateCtrl, templateUrl:'detail.html'}).
otherwise({redirectTo:'/'});
});
나는 아마도 무슨 일이 일어나고 있는지 설명하는 것이 지금까지 찾을 수있는 유일한 방법은 "주입 서비스 속 컨트롤러"를 설명하는 $location
, $timeout
하지만 방법 매개 변수하지 angularFire
와 fbURL
.
내 구체적인 질문은 다음과 같습니다.
컨트롤러 매개 변수는 무엇 일 수 있습니까?
컨트롤러 함수는 매개 변수와 함께 어디에서 호출됩니까? 또는 매개 변수가 호출되지 않고 Angular.js 마법이 많이 발생하는 컨트롤러와 관련된 것입니다 (그렇다면 github에서 소스 코드를 볼 수 있습니까)?
어디에
angularFire
정의되어 있습니까?fbURL
in 매개 변수 는 다음 과 어떻게 연결 됩니까?angular.module('project', ['firebase']). value('fbURL', 'https://angularjs-projects.firebaseio.com/'). factory ...
Angular.js가 제공하는 모든 서비스 (예 :
$location
및$timeout
)를 볼 수있는 곳이 있습니까? (목록을 찾으려고했지만 실패했습니다.)
컨트롤러 매개 변수는 무엇 일 수 있습니까?
제어기 변수는 종속 되고, 주입 AngularJS와 인젝터 서비스. 그들은 무엇이든 될 수 있습니다. 그러나 일반적으로 컨트롤러 내부에서 사용되는 서비스 입니다.
컨트롤러 함수는 매개 변수와 함께 어디에서 호출됩니까?
컨트롤러뿐만 아니라 지시어, 필터, 서비스 및 AngularJS의 다른 많은 것들이 함수 입니다. 그러나 프레임 워크는 이러한 함수가 호출 되는 시기 와 방법을 많이 관리합니다 .
연관된 물건 이라고 부르는 이름 은 위에서 언급했듯이 dependency 라는 이름이 있습니다. 마술 이라고 부르는 것은 작동중인 AngularJS 종속성 주입 메커니즘입니다.
이러한 함수 (컨트롤러 및 기타)가 인젝터에 의해 호출되면 매개 변수 이름 (예 :
$scope
또는$http
또는angularFire
) 을 읽고 해당 이름 으로 등록 된 서비스를 검색 한 다음 함수가 호출 될 때 매개 변수로 제공됩니다.간단하다. 인젝터에 대한 "종속성"(인젝터가 관리하는 매개 변수)에 대해 지시하는 여러 가지 방법이 있습니다.
단순히 함수를로 선언
function myCtrl($scope) {}
하면 인젝터가$scope
매개 변수 이름에서 서비스 를 찾을 수 있습니다 . 당신은하지만 작게를 자바 스크립트 코드를 매개 변수 이름은 "a"또는 "X"와 같은 작은 문자열을 수정할 수 있기 때문에, 인젝터는 더 이상 서비스를 찾을 수 없습니다. 이 문제를 방지하려면 배열 표기법을 사용하여 삽입 할 서비스 이름을 지정할 수 있습니다 . 이 경우 다음과 같이 함수를 선언합니다.myCtrl = ['$scope', function($scope) {}]
AngularJS 세계에서 많은 배열 표기법 사용을 볼 수 있습니다. 이제 당신은 그것을 이해하기 시작합니다. 함수에 다른 이름 을 삽입
$scope
하여angularFire
사용할 수도 있습니다 (이름 변경은 권장되지 않습니다 .이 예제는 학습 목적으로 제공됩니다) .-이렇게하면 함수 내에서 $ scope를 "skop"로 사용하고 angularFire를 다음과 같이 사용할 수 있습니다. "af". 순서 배열의 서비스는 매개 변수의 순서와 일치합니다.['$scope', 'angularFire', function(skop, af) {}]
다른 예시:
var myController = ['$scope', '$resource', '$timeout',
function($scope, $resource, $timeout) {
// this controller uses $scope, $resource and $timeout
// the parameters are the dependencies to be injected
// by AngularJS dependency injection mechanism
}
];
angularFire는 어디에 정의되어 있습니까?
에서 중포 기지 모듈 .
이미 알고 있듯이 인젝터는 해당 "사물" 이름이 등록되어 있고 기록에 사용 가능한 한 모든 것을 주입 합니다. 해당 이름 의 "서비스"가있는 경우 그는이를 제공 할 수 있습니다.
그러면
name => stuff
인젝터가 사용하는 이 목록은 어떻게 작성됩니까?모듈 이 답입니다. 모듈 의 목록보다 조금 더입니다
name => stuff
. 서비스, 팩토리, 필터, 지시문 등을 등록 하는 모듈 에 있습니다.공식 문서에서 Module 메소드를 주의 깊게 살펴보십시오 . 거의 모든 메소드가 매개 변수로 수신됩니다 : name 및 일부 " stuff "(여기서 "stuff"는 거의 항상 함수 , 컨트롤러 또는 팩토리 또는 지시문 정의) ). 지정된 이름을 통해 주입 할 수있는 것은이 모든 "물건"입니다 .
"$ timeout", "$ http"등과 같은 AngularJS 서비스는 ng 모듈 이 이미 프레임 워크에 의해로드 되었기 때문에 기본적으로 사용할 수 있습니다 .
추가 서비스의 경우 모듈 을로드 / 요구해야합니다 . 당신이 무엇을 그의 ngRouter , 중포 기지 적재에 의해 ... 등, 모듈 , 등록 된 물건은 주입 할 수 있는 당신의 모듈 / 응용 프로그램.
단계별 예를 살펴 보겠습니다.
// An empty module:
var module = angular.module('myModule', []);
// Now, adding an "injectable" constant:
module.constant('niceStuff', { blip: 'blop', blup: 307 });
// We could add a service:
module.service('entityManager', ['$http', function($http){ }]);
// and so on... if I wanted to use "$resource" instead of "$http"
// in the entityManager service above...
// ...I would need to require the ngResource when creating the module above,
// like this: var module = angular.module('myModule', ['ngResource']);
// because "$resource" is not available by default
// NOW, anywhere else, since the code above already ran
// I can use those NAMES as dependencies like this:
// We are creating another module now:
var koolModule = angular.module('km', ['myModule']);
// Note that I am requiring the previous module through its registered name
// Now, anything I've declared in that module
// - just like "ng" (by default) and "firebase" (required) does -
// is available for "injection"!!!
koolModule.controller('koolController',
['niceStuff', 'entityManager', function(niceStuff, entityManager) {
console.log(niceStuff.blip); // 'blop'
console.log(niceStuff.blup + 10); // 317
}]
);
이것이 angularFire와 같은 firebase 항목을 사용할 수있는 방법입니다! 우리는 무엇을 했습니까? 먼저 "myModule"을 만들고 NAMED 항목을 등록했습니다. 나중에 "koolModule"에 "myModule"이 필요했습니다.이 이름은 이미 주입기 name => stuff
목록 에서 사용할 수 있습니다 .
매개 변수의 fbURL은 어떻게 연결됩니까?
As we've just seen, most module methods are merely registering things - giving names to things so they can be injected and/or used through these names later.
When
module.value('fbURL', 'https://angularjs-projects.firebaseio.com/')
is called, fbURL (and the specified value) is registered into thename => stuff
list... in this case, the name is "fbURL", and the value/stuff is the URL string - but it could be anything!Is there a place where I can see all the services, e.g. $location and $timeout, that Angular.js provides?
Yes, the API reference: http://docs.angularjs.org/api/
Pay attention at how the left-side navigation is organized... by modules! First, the ng module, with tons of directives, services, filters, etc. Then, below, the other modules (ngRoute, ngResource, ngMock, and so on), each one containing their own services, fitlers or directives...
Thanks for the opportunity of sharing these thoughts. I enjoyed writing them.
As per toxaq comment, here is the comments as an answer
What can the controller parameters be?
It can mostly be services, factories, values, constants, etc... that you have defined somewhere before OR using resolve on a route definition.
Where are the controller functions called with their parameters?
Here is the proper way to define a controller:
angular.module('project').controller('EditCtrl', [ '$scope', '$location', '$routeParams', 'angularFire', 'fbURL', function($scope, $location, $routeParams, angularFire, fbURL) { ... } ]);
That way, you first set the name of the services that you want to inject, and then you give those services a different name if you would like. In fact, this is mandatory if you want to minimize your angular code later (since the minimization will rename the variables, angular needs to still be able to find the services names).
Where is angularFire defined?
When you defined your project module, you also included the firebase module dependancy. Inside of the firebase module, there must be an angularFire service like the previous fbURL.
How is the fbURL in the parameter linked to
Like you seem to understand, the parameters of the controller are being injected by angular from the definition of the controller. Angular will look in all the registered services and try to find a match with the specified name of the parameter and inject the according service!
Is there a place where I can see all the services, e.g. $location and $timeout, that Angular.js provides?
For the list of all built in services, filters, directives included in Angular, have a look at the API: http://docs.angularjs.org/api
Where are the controller functions called with their parameters?
Controller functions are instantiated with the ngController directive or if you have mentioned the controller during the route creation using $routeProvider
. AngularJS does this tranperently for you and injects the parameters that you have defined on your controller using DI
.
The DI works by matching the names (or some times order) of the parameters. So $scope
would get the current scope, $http
would get the http service
First off great job choosing this framework. It is the best. Those variables you see with the $ sign are injected and part of the standard framework. These services will make your life so much easier. The best way to think of controllers are they are script sheets. They help separate the code. Do not think of them as methods. Those variables you see such as $timeout & $scope are services that will come in handy as you need certain things done. All documentation for the framework is at http://docs.angularjs.org/api/ but I would start with this tutorial http://docs.angularjs.org/tutorial/ .
The angularfire is not part of the framework. It is another service that leverages the framework in order to create a powerful real time distributed network. When you load the angularfirejs it comes with the service which is then injected as the parameter you see.
To answer your second question, the parameters you pass could be anything so long as you make a corresponding service. Please refer to this to make your own parameter for controllers : http://docs.angularjs.org/guide/dev_guide.services.creating_services
fbURL is just a variable that you can create and the code you placed in your question is simply the instruction on how to make it.
Angularjs is not the type of framework you can learn by looking at what it offers. Simply because it offers it all. Everything you could possibly bring to make a great app. Instead you should focus on asking google how to solve your problem with angular.
Also check out videos on youtube. You will find some great ones.
참고URL : https://stackoverflow.com/questions/19238191/understanding-angular-js-controller-parameters
'program story' 카테고리의 다른 글
rbenv에서 루비 버전 제거 (0) | 2020.10.12 |
---|---|
iPhone / iPod touch 용 Safari iOS 7에서 내비게이션 막대를 숨길 수 없음 (0) | 2020.10.12 |
Visual Studio Code에서 열린 폴더를 닫는 방법은 무엇입니까? (0) | 2020.10.12 |
“npm -d install”에서“-d”는 무엇입니까? (0) | 2020.10.12 |
Java에서 toString ()을 올바르게 재정의하는 방법은 무엇입니까? (0) | 2020.10.12 |