Unable to inject `$http` using AngularJS explicit

2019-04-06 19:58发布

问题:

I have been told that I should be using the app.controller syntax, in order to support minification.

Rewriting the sample (tutorial) example, and I found that I couldn't get it to work:

use 'strict';

/* Minifiable solution; which doesn't work */
var app = angular.module('myApp', ['ngGrid']);

// phones.json: http://angular.github.io/angular-phonecat/step-5/app/phones/phones.json

app.controller('PhoneListCtrl', ['$scope', '$http', function ($scope, $http) {
    $http.get('phones/phones.json').success(function (data) {
        $scope.phones = data;
    });

    $scope.orderProp = 'age';
}]);
/* Alternate [textbook] solution; which works */
function PhoneListCtrl($scope, $http) {

    $http.get('phones/phones.json').success(function (data) {
        $scope.phones = data;
    });

    $scope.orderProp = 'age';
}

PhoneListCtrl.$inject = ['$scope', '$http'];
<body ng-app="myApp" ng-controller="PhoneListCtrl">
    {{phones | json}}
</body> <!-- Outputs just an echo of the above line, rather than content -->

What do I need to change?

回答1:

The way I did my controller layout is:

var app = angular.module('myApp', ['controllers', 'otherDependencies']);
var controllers = angular.module('controllers', []);
controllers.controller('PhoneListCtrl', ['$scope', '$http', function ($scope, $http) {
  // your code
  $http.get('phones/phones.json').success(function (data) {
    $scope.phones = data;
  });
}]);