【发布时间】:2023-03-05 22:02:01
【问题描述】:
我是打字稿的新手,我正在尝试将此角度控制器转换为打字稿,但我遇到了 $scope.$on() 的问题。
(function () {
'use strict';
angular.module('controllers').controller('NavigationController', ['$scope', '$location', 'NavigationServices',
function ($scope, $location, NavigationServices) {
var vm = this;
vm.isSideBarOpen = NavigationServices.getSideBarState();
vm.toggleSideBar = function () {
NavigationServices.toggleSideBar();
};
$scope.$on('navigation:sidebar', function (event, data) {
vm.isSideBarOpen = data;
});
}]);
})();
我尝试过的打字稿:
module app.controllers {
import IScope = ng.IScope;
import ILocationService = ng.ILocationService;
import INavigationServices = app.services.INavigationServices;
interface INavbarController {
isSidebarOpen: boolean;
toggleSideBar(): void;
}
class NavbarController implements INavbarController {
isSidebarOpen: boolean;
static $inject = ['$scope', '$location', 'NavigationServices'];
constructor(private $scope: IScope, private $location: ILocationService, private NavigationServices: INavigationServices){
var _this = this;
_this.isSidebarOpen = this.NavigationServices.getSideBarState();
this.$scope.$on('navigation:sidebar', (event: ng.IAngularEvent, data: boolean) => {
_this.isSidebarOpen = data;
});
}
toggleSideBar(): void {
this.NavigationServices.toggleSideBar();
}
}
angular.module('controllers')
.controller('NavigationController', NavbarController);
}
我没有收到任何错误,但它不起作用。没有打字稿,一切都很好。
这里是 NavigationServices 工厂:
module app.services {
'use strict';
export interface INavigationServices {
toggleSideBar(): void;
getSideBarState(): boolean;
closeSideBar(): void;
openSideBar(): void;
}
class NavigationServices implements INavigationServices {
private isSideBarOpen: boolean;
constructor(private $rootScope: ng.IRootScopeService) {
this.isSideBarOpen = false;
}
toggleSideBar(): void {
this.isSideBarOpen = !this.isSideBarOpen;
this.$rootScope.$broadcast('navigation:sidebar', this.isSideBarOpen);
}
getSideBarState(): boolean {
return this.isSideBarOpen;
}
closeSideBar(): void {
this.isSideBarOpen = false;
this.$rootScope.$broadcast('navigation:sidebar', this.isSideBarOpen);
}
openSideBar(): void {
this.isSideBarOpen = true;
this.$rootScope.$broadcast('navigation:sidebar', this.isSideBarOpen);
}
}
angular.module('services').factory('NavigationServices', ['$rootScope', ($rootScope) => new NavigationServices($rootScope)]);
}
谢谢。
【问题讨论】:
-
不只是
$scope.$on吗? -
尝试了 $scope.$on(...) ,构造函数采用了私有和公共 $scope,什么都没有。
标签: javascript angularjs typescript