我有一个AngularJS指令,我在几个页面中使用,但每次都有点不同。所以我想保留我的全局指令,然后创建这个指令的实现来覆盖一些函数,同时仍然使用全局函数。
“父母”指令:
'use strict';
angular.module('app.leaderBoardDirective')
.directive('fooLeaderBoard', LeaderBoard);
LeaderBoard.$inject = [];
function LeaderBoard(
) {
var directive = {
restrict: 'EA',
replace: false,
templateUrl: 'foo/leaderBoard.template.html',
scope: {
***someParams***
},
controller: LeaderBoardDirectiveController,
controllerAs: 'vm',
bindToController: true
};
return directive;
LeaderBoardDirectiveController.$inject = [
***'dependencies'***
];
function LeaderBoardDirectiveController(
***dependencies***
) {
/* A LOT OF FUNCTIONS/VARS */
}
}
“儿童”指令: 这是排行榜,但显示在房间页面上,因此需要一些 不同的功能,比如每个玩家的踢球按钮。
'use strict';
angular.module('app.roomPage')
.directive('fooRoomLeaderBoard', RoomLeaderBoard);
RoomLeaderBoard.$inject = [];
function RoomLeaderBoard() {
var directive = {
restrict: 'EA',
replace: false,
templateUrl: 'foo/leaderBoard.template.html',
scope: {
***same params that in the parent***
},
controller: RoomLeaderBoardDirectiveController,
controllerAs: 'vm',
bindToController: true
};
return directive;
RoomLeaderBoardDirectiveController.$inject = [
'$controller',
'$scope'
];
function RoomLeaderBoardDirectiveController(
$controller,
$scope
) {
var vm = this;
/* here, I tried to extend my child directive's controller
with the parent directive's one to access his functions and maybe
override some of them
*/
angular.extend(vm, $controller('LeaderBoardDirectiveController',
{$scope: $scope}));
}
}
当然,我通过调用相应的模块导入了我的指令,但是当我执行angular.extend时,我收到一个错误,指出控制器fooLeaderBoard没有注册。
顺便说一下,我的父指令已经使用了与API通信的服务,但我只想避免重复的代码。