Location>code7788 >text

Two ways to write injected dependencies and services for controllers that control views in angularjs

Popularity:151 ℃/2024-09-28 11:29:11

In AngularJS, controllers are important components used to control the behavior of the view. When defining a controller, there are two main ways to inject dependencies:

1. Explicit dependency injection, polyglot uses an array of strings to inject dependencies:

('myCtrl', ['$scope', function($scope) {
$ = [];
}]);

 

In this approach, the dependencies (in this case `$scope`) are listed explicitly as strings. This approach, called "explicit dependency injection", makes dependencies more visible and helps with testing because it is easier to provide mock objects for dependencies. This is an officially recommended practice in AngularJS because it avoids problems caused by scope chaining and helps improve code maintainability. The parameter name of function($scope) in this way of writing is$scopeChanges can be made inside the function without affecting the execution of the code, because AngularJS looks up the corresponding dependencies based on the names in the string array. For example, you can change a function parameter to any other name, as shown below:

('myCtrl', ['$scope', function(myCustomScopeName) {
     = [];
}]);

As long as the first array element'$scope'Remaining unchanged, AngularJS will be able to correctly$scopeInstances are injected into the instance namedmyCustomScopeNamein the parameters of the

2. Hidden dependency injection, i.e., the form of passing the name of a dependency directly:

('myCtrl', function($scope) {
$ = [];
});

In this approach, dependencies (e.g. `$scope`) are passed directly to the constructor as arguments. While this approach is succinct, it relies on the parser being able to correctly parse out the function parameter names and match them to the service names. This can lead to problems during the development phase, especially when some JavaScript optimization tools (such as closure compilers) compress the code, which can change the variable names and cause the injection to fail. In this way of writing, the function parameter $scope of function($scope) will not be able to change its name. Otherwise AngularJS will not be able to recognize and inject the correct service, resulting in an error.

Overall, the first approach (explicit dependency injection) is safer and easier to debug and test, while the second approach, although simple, may cause some problems in large projects. Therefore, it is recommended to use the first method to define your controller.