Angular problem with component controller

Angular 1.5 introduced components (special type of directive)

For the directive we can write:

app.directive('myDirective', ['$timeout','$mdToast','$rootScope', // <-- injection function ($timeout, $mdToast,$rootScope) { return { link: {}, //... } } 

How can we write an injection for components?

Of course, I can write something like:

 app.component('myComponent', { restrict: 'E', bindings: { data: '=' }, templateUrl: 'template.html', controllerAs: 'vm', controller: 'myComponentCtrl' }); 

and

 app.controller('myComponentCtrl', ['$scope', '$timeout', function ($scope, $timeout) { // .... }]); 

But I want to write a built-in controller, for example:

 app.component('myComponentCtrl', { templateUrl: 'template.html', controller: function($scope, $timeout) { //... } }); 

The aforementioned style styling (GRUNT) will slow down my Unknown provider: aProvider <- a code Unknown provider: aProvider <- a ,

So how to write injections for components?

Any ideas?

In the demo I use Plunker

+5
source share
2 answers

You need to wrap controller: function($scope, $timeout) { in minification syntax.

I'm not really a fan of the inline, but:

 app.component('myComponentCtrl', { templateUrl: 'template.html', controller: ['$scope', '$timeout', function($scope, $timeout) { //... }] }); 

Pure form:

 app.component('myComponentCtrl', { templateUrl: 'template.html', controller: myComponentCtrl }) myComponentCtrl.$inject = ['$scope', '$timeout']; /* @ngInject */ function myComponentCtrl($scope, $timeout) { //... } 

The third option is to use ng-annotate, and you can delete the line myComponentCtrl.$inject = ['$scope', '$timeout']; above.

+9
source

You can simply use array notation for your controller.

 app.component('myComponent', { restrict: 'E', bindings: { data: '=' }, templateUrl: 'template.html', controllerAs: 'vm', controller: ['$scope', function ($scope) { }] }); 

However, I prefer to use a tool like ng-annotate in my build pipeline, which automatically converts your injections to array notation, so your source code should not worry about that.

+3
source

Source: https://habr.com/ru/post/1243974/


All Articles