我是打字稿的新手,我正在尝试将此角度控制器转换为打字稿,但我遇到了 $ 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)]);
}
感谢。
答案 0 :(得分:1)
在分配了更多调试后,我注意到$ scope。$ on正在触发,_this.isSidebarOpen正在更新。我注意到在js文件中 vm.isSideBarOpen 包含一个CAPITAL B,而在typescript中是小写的。因此,视图和控制器之间的绑定被破坏了。我将_this.isSidebarOpen改为_this.isSideBarOpen,一切都很完美。
答案 1 :(得分:0)
对不起。我编辑了我的回复。以前的答案是正确的。仍然需要为观看注入$ scope并听取事件