我正在研究是否可以在1.4中采用指令并尝试类似于1.5组件。我使用bindToController
和controllerAs
在我的指令中使用控制器而不是单独的控制器。我已经成功地将导出作为一个函数完成了,但是想看看我是否可以作为一个类导出,看看是否有充分的理由这样做。我现在遇到bindToController
错误,其中包含以下代码:
export default class recordingMenuComponent {
constructor(RecordingCtrl) {
'ngInject';
this.restrict = 'E',
this.scope = {},
this.templateUrl = '/partials/media/recording/recording-menu.html',
this.controller = RecordingCtrl,
this.controllerAs = 'record',
this.bindToController = {
video: '='
}
}
RecordingCtrl($log, $scope, $state, $timeout, RecordingService) {
'ngInject';
const record = this;
Object.assign(record, {
recentCalls: record.recentCalls,
startRecording() {
let video = {
accountId: $scope.accountId,
title: record.sipUrl
};
RecordingService
.recordVideoConference(video, record.sipUrl, record.sipPin, 0)
.then(result => {
video.id = result.id;
$timeout(() => $state.go('portal.video', {videoId: video.id}), 500);
}, error => $log.error('Error starting the recording conference: ', error));
},
getRecentCalls() {
RecordingService
.recentVideoConferenceCalls()
.then(result => {
record.recentCalls = result;
}, error => $log.error('There was an error in retrieving recent calls: ', error));
}
});
}
static recordingFactory() {
recordingMenuComponent.instance = new recordingMenuComponent();
return recordingMenuComponent.instance;
}
}
然后导入:
import angular from 'angular'
import recordingMenuComponent from './recordingMenuComponent'
angular.module('recordingModule', [])
.directive(recordingMenuComponent.name, recordingMenuComponent.recordingFactory);
为简洁起见,我遗漏了一些模块,与尝试将此指令转换为组件无关。请注意,我尝试不在.controller()
之前使用.directive()
。
当我尝试使用它时,我收到此错误:
angular.js:9490 Error: [$compile:noctrl] Cannot bind to controller without directive 'recordingMenuComponent's controller
我不确定我是走在正确的轨道上还是这不是正确的道路。
感谢您的帮助。
答案 0 :(得分:1)
您应该将RecordingCtrl
实现为类
const app = require('../app');
class RecordingCtrl {
static $inject = ['$log', 'RecordingService'];
constructor($log, recordingService) {
this.$log = $log;
this.recordingService = recordingService;
}
startRecording() {
// . . .
}
recentCalls() {
// . . .
}
}
// for ng15 component
const recordingMenu = {
restrict: 'E',
scope = {},
templateUrl = '/partials/media/recording/recording-menu.html',
controller = RecordingCtrl,
controllerAs = 'record',
bindToController = {
video: '='
}
}
app.component('recordingMenu', recordingMenu);
// or ng1.4 directive
function recordingMenu() {
return {
restrict: 'E',
scope = {},
templateUrl = '/partials/media/recording/recording-menu.html',
controller = RecordingCtrl,
controllerAs = 'record',
bindToController = {
video: '='
}
}
}
app.directive('recordingMenu', recordingMenu);
将控制器实现为类方法确实有意义。
这意味着您将拥有两个类...除非您只是想让指令定义对象工厂成为控制器的普通函数或静态方法。
答案 1 :(得分:0)
即使不是最好的方法,我也能够正常工作。这是为了实验和我能够让它运作的方式:
.directive(recordingMenuComponent.name, () => new recordingMenuComponent())