chr*_*olr 5 javascript angularjs typescript
我是打字稿新手,我正在尝试将此角度控制器转换为打字稿,但我在$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;
});
}]);
})();
Run Code Online (Sandbox Code Playgroud)
我尝试过的打字稿:
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);
}
Run Code Online (Sandbox Code Playgroud)
我没有收到任何错误,但它不起作用。没有打字稿,一切都运行良好。
这是 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)]);
}
Run Code Online (Sandbox Code Playgroud)
谢谢。
经过更多调试后,我注意到 $scope.$on 正在触发并且 _this.isSidebarOpen 正在更新。我注意到在 js 文件中vm.isSideBarOpen包含大写字母 B,在打字稿中是小写。因此,视图和控制器之间的绑定被破坏。我将 _this.isSidebarOpen 更改为 _this.isSideBarOpen,一切工作正常。
| 归档时间: |
|
| 查看次数: |
6452 次 |
| 最近记录: |