Angular 1.5引入了components(特殊指令)
对于指令,我们可以写:
app.directive('myDirective',
['$timeout','$mdToast','$rootScope', // <-- injection
function ($timeout, $mdToast,$rootScope) {
return {
link: {},
//...
}
}
我们如何为组件编写注入?
我确实可以写,比如:
app.component('myComponent', {
restrict: 'E',
bindings: {
data: '='
},
templateUrl: 'template.html',
controllerAs: 'vm',
controller: 'myComponentCtrl'
});
和
app.controller('myComponentCtrl',
['$scope', '$timeout',
function ($scope, $timeout) {
// ....
}]);
但我想编写内置控制器,例如:
app.component('myComponentCtrl', {
templateUrl: 'template.html',
controller: function($scope, $timeout) {
//...
}
});
上面提到的样式缩小(GRUNT)将会激活我的代码Unknown provider: aProvider <- a
,
那么如何为组件正确编写注入?
有什么想法吗?
我使用的演示 Plunker
答案 0 :(得分:10)
您需要在缩小语法中包含controller: function($scope, $timeout) {
。
我实际上不是内联的粉丝,但是:
app.component('myComponentCtrl', {
templateUrl: 'template.html',
controller: ['$scope', '$timeout', function($scope, $timeout) {
//...
}]
});
清洁形式:
app.component('myComponentCtrl', {
templateUrl: 'template.html',
controller: myComponentCtrl
})
myComponentCtrl.$inject = ['$scope', '$timeout'];
/* @ngInject */
function myComponentCtrl($scope, $timeout) {
//...
}
第三个选项是使用ng-annotate,您可以删除上面的myComponentCtrl.$inject = ['$scope', '$timeout'];
行。
答案 1 :(得分:4)
您可以继续使用控制器的数组表示法。
app.component('myComponent', {
restrict: 'E',
bindings: {
data: '='
},
templateUrl: 'template.html',
controllerAs: 'vm',
controller: ['$scope', function ($scope) {
}]
});
我更喜欢做的是在我的构建管道上使用ng-annotate之类的工具自动将您的注入转换为数组表示法,因此您的源代码无需担心这一点。