无法使用AngularJS显式`app.controller`语法注入`$ http`?

时间:2013-05-21 07:22:20

标签: javascript angularjs dependency-injection controller angularjs-scope

been told我应该使用app.controller语法,以支持缩小。

重写示例(教程)示例,我发现我无法让它工作:

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 -->

我需要改变什么?

1 个答案:

答案 0 :(得分:13)

我执行控制器布局的方式是:

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;
  });
}]);