Angular打字稿控制器中的“状态未定义”

时间:2016-02-16 16:30:23

标签: javascript angularjs controller typescript angular-ui-router

我是打字稿的新手,我正在尝试使用UI Router's $state在我的打字稿控制器中导航。不幸的是,我仍然收到state is not defined错误,我无法解决。

这是我的控制器:

module MyApp {
export class LoginController {
    email: string;
    password: string;
    loginForm: any;
    state: any;

    constructor($state: ng.ui.IStateProvider) {
        this.state = $state;
    };

    login() {
        if (this.loginForm.$invalid) {
            return;
        }

        console.log(`Login was clicked, email is ${this.email} and password is ${this.password}`);
        state.go('Dashboard');
    }
}
}

angular.module('myApp').controller('loginController', MyApp.LoginController);

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:4)

您正在为控制器构建分配$statethis.state

这意味着它应该在整个对象上被称为this.state

答案 1 :(得分:0)

您需要使用this.state访问登录功能中的$state变量。您可以查看以下更正的代码实现。

JSFiddle Typescript Implementation

// Typescript

module MyApp {
  export class LoginController {
    email: string;
    password: string;
    loginForm: any;
    state: any;

    constructor($state: ng.ui.IStateProvider) {
      this.state = $state;
    };

    login() {

      if (this.loginForm.$invalid) {
        this.formError = "invalid form data";
        return;
      }

      this.formError = "";

      console.log(`Login was clicked, email is ${this.email} and password is ${this.password}`);
      this.state.go('Dashboard');
    }
  }
}

let app = angular.module('myApp', ['ui.router'])
app.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('login', {
      url: '/login',
      template: `
      	<div ng-controller="loginController as lc">
          <form name="lc.loginForm" ng-submit="lc.login()">
            <div>Email:<input ng-model="lc.email" ng-required="true" /></div>
            <div>Password: <input ng-model="lc.password" ng-required="true" /></div>
            <button type="submit" ng-click="lc.login()">Click</button>
          </form>
        </div>      
      `
    })
    .state('Dashboard', {
      url: '/Dashboard',
      template: '<div> I am Dashboard </div>'
    });

  $urlRouterProvider.otherwise('/login');
});

app.controller('loginController', MyApp.LoginController);
<!-- HTML -->
<div ng-app="myApp">
  <div ui-view></div>
</div>