Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to inject `$http` using AngularJS explicit `app.controller` syntax?

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?

like image 776
user2283066 Avatar asked May 21 '13 07:05

user2283066


People also ask

What is$ inject in AngularJS?

Dependency Injection in AngularJS can be defines as the software design pattern which defines the way the software components are dependent on each other. AngularJS provides a set of components that can be injected in the form of dependencies such as factory, value, constant, service, and provider.

How does Dependency Injection work in AngularJS?

Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies. The AngularJS injector subsystem is in charge of creating components, resolving their dependencies, and providing them to other components as requested.

Which component can be injected as a Dependency in AngularJS?

The "Application Module" can be injected as a dependency in AngularJS.

What is Dependency Injection in Angular?

Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need.


1 Answers

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;
  });
}]);
like image 194
Foo L Avatar answered Oct 13 '22 06:10

Foo L