V
V
vasIvas2015-07-04 23:36:19
JavaScript
vasIvas, 2015-07-04 23:36:19

Why service is not created?

<body ng-app="app">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
  <script src="jquery-2.1.4.min.js"></script>
  <div ng-controller="MainController"></div>
  <script>
    var app = angular.module('app', []);

    app.service('$myService', function(){

    });

    app.controller('MainController', ['$scope', function($scope, $myService){
      console.log($myService); // почему $myService undefined?
    }]);
  </script>
</body>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
D', 2015-07-05
@vasIvas

Because it should be like this:

<body ng-app="app">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
  <script src="jquery-2.1.4.min.js"></script>
  <div ng-controller="MainController"></div>
  <script>
    var app = angular.module('app', []);

    app.service('$myService', function(){
       return {hello: 'world'};
    });

    app.controller('MainController', ['$scope', '$myService', function($scope, $myService){
      console.log($myService); // почему $myService undefined?
    }]);
  </script>
</body>

Specifically, this line:
This way of writing is called " inline array annotation ". You can read more about him here .
In short:
Angular automatically detects the objects you pass to a function by their names.
That is, if we pass $myService to the controller, then Angular will look for a directive/factory/filter/etc with that name, and substitute it in the parameters.
When we use JS code obfuscators/minimizers, the variable names can be changed in the final code, and Angular will not understand what we want to pass to the function.
To solve this problem, the Angular developers have added an additional syntax (array notation).
We can pass as the second parameter an array in which we specify the names of all the objects we need, and as the last parameter we can specify a function that takes ALL these parameters, in the same order.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question