AngularJS控制器中$scope、$http与scope、http的含义咨询
Hey there! Let’s break down this controller code line by line—this syntax is tied to AngularJS’s core dependency injection system, which is a common point of confusion when starting out, so you’re definitely not alone.
What’s the deal with ['$scope', '$http']?
This array syntax is AngularJS’s safe, production-ready way to declare dependencies for your controller. Here’s why it matters:
$scopeand$httpare built-in AngularJS services.$scopeacts as the bridge between your controller and the view (you’ll use it to pass data or methods to your HTML), and$httpis the service you’ll rely on to make HTTP requests (like fetching that JSON data you’re working on).- The string names (
'$scope','$http') are critical because they prevent breakage when you minify or compress your code. When code is minified, variable names get shortened (e.g.,$scopemight becomes), but strings stay intact. AngularJS uses these string identifiers to know exactly which services to inject into your controller.
What about the function parameters (scope, http)?
These are just aliases for the injected services—you can name them anything you want, as long as their order matches the order of the services in the array. For example:
- The first parameter
scopereceives the instance of the$scopeservice (matching the first string in the array). - The second parameter
httpreceives the instance of the$httpservice (matching the second string in the array).
You could just as well write:
abc.controller('abcCtrl', ['$scope', '$http', function(myScope, myHttp){ // Use myScope instead of $scope here to pass data to the view // Use myHttp.get() to fetch your JSON data }]);
The golden rule here is: the order of parameters must exactly match the order of service names in the array.
A quick example to tie it all together
Here’s how you’d use this setup to actually fetch JSON data with $http:
abc.controller('abcCtrl', ['$scope', '$http', function(scope, http){ // Fetch JSON data from a target URL http.get('your-data-source.json') .then(function(response) { // Assign the fetched data to scope so your view can access it scope.fetchedJson = response.data; }) .catch(function(error) { // Handle any request errors console.error('Oops, failed to fetch data:', error); }); }]);
What if I skip the array syntax?
You might see shorter code like this in examples:
abc.controller('abcCtrl', function($scope, $http){ });
This works fine in development, but it will break when you minify your code—since minifiers will rename $scope and $http to shorter, unrecognizable names, AngularJS won’t know which services to inject. The array syntax is the safe, reliable choice for production.
内容的提问来源于stack exchange,提问作者Code lover

