本文介绍了无法使用 AngularJS 显式 `app.controller` 语法注入 `$http`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

被告知我应该使用 app.controller 语法,以便支持缩小.

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

我需要改变什么?

推荐答案

我的控制器布局方式是:

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

这篇关于无法使用 AngularJS 显式 `app.controller` 语法注入 `$http`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 18:49