【问题标题】:'state is not defined' in Angular typescript controllerAngular 打字稿控制器中的“未定义状态”
【发布时间】:2016-05-28 01:06:46
【问题描述】:

我是 typescript 的新手,我正在尝试使用 UI Router's $state 在我的 typescript 控制器中导航。不幸的是,我仍然收到无法解决的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);

任何帮助将不胜感激。

【问题讨论】:

  • 我正在使用Angular 1.5

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


【解决方案1】:

您需要使用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>

【讨论】:

    【解决方案2】:

    您在控制器构造时将$state 分配给this.state

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

    【讨论】:

      猜你喜欢
      • 2016-04-28
      • 1970-01-01
      • 2017-10-23
      • 2019-01-26
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 2016-06-20
      相关资源
      最近更新 更多