我正在研究是否可以在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
我不确定我是否走上了正确的道路,或者说这条路是不对的。
谢谢你的帮助。
发布于 2016-06-20 16:18:57
您应该将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);
将控制器实现为类方法是没有意义的。
这意味着你会有两个班..。除非您只想使指令定义对象工厂成为一个简单的老函数或您的控制器的静态方法。
发布于 2016-06-20 17:19:47
即使这不是最好的方法,我也能让它发挥作用。它是为了实验和我能够让它发挥作用的方式:
.directive(recordingMenuComponent.name, () => new recordingMenuComponent())
https://stackoverflow.com/questions/37926930
复制相似问题