【问题标题】:angular showing TypeError: Cannot read property 'state' of undefined角度显示类型错误:无法读取未定义的属性“状态”
【发布时间】:2016-01-30 03:25:07
【问题描述】:

我正在尝试通过使用将替换 ajax 的 angular 添加到我的 rails 应用程序中的特定页面的路由来学习路由。以下是控制台错误。

未捕获的错误:[$injector:modulerr] 无法实例化模块 testApp 由于:TypeError: Cannot read property 'state' of undefined

这是我定义的。

app.js

app = angular.module("testApp", ['ui.router']);

app.config([
    function ($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('mylistings', {
                url: '/mylistings',
                templateUrl: '/views/mylistings.html',
                controller: 'dashboardCtrl'
            });
    }
]);

app.controller('dashboardCtrl', function ($scope, $http, $stateParams) {
$scope.testing="testdata"
});

mylistings.html

{{testing}}

在这种情况下,http://localhost:3000/dashboard 是我要路由的 url。有人可以告诉我这里做错了什么。

【问题讨论】:

  • 配置中没有显示 url /dashboard
  • @charlietfl 我希望它类似于localhost:3000/dashboard#mylistings...
  • localhost:3000/dashboard 来自我的 Rails 应用程序,而不是角度。我想在这里路由,因为我想要一个不同的部分 localhost:3000/dashboard#mybookings 和其他一些
  • 应该有一个使用$urlRouterProvider.otherwise('/');的默认设置和一个与该url匹配的状态。现在如果你去http://localhost:3000/dashboard 那么路由器不知道该怎么做

标签: javascript ruby-on-rails angularjs


【解决方案1】:

问题在于配置函数的定义。 如果您使用数组app.config([]),这意味着您为准备缩小的依赖项编写安全代码。语法是:

app.config(['$arg1', '$arg2', function ($arg1, $arg2) {
   }]);

所以当代码被缩小时,你会得到类似的东西:

app.config(['$arg1', '$arg2',function(a,b) {}]);

app.js 的示例中,如果您想编写安全的代码以进行缩小(如果您不使用 ng-annotate),请将配置更改为以下代码:

app = angular.module("testApp", ['ui.router']);

app.config(['$stateProvider','$urlRouterProvider',
    function ($stateProvider, $urlRouterProvider) {
        $stateProvider
            .state('mylistings', {
                url: '/mylistings',
                templateUrl: '/views/mylistings.html',
                controller: 'dashboardCtrl'
            });
    }
]);

app.controller('dashboardCtrl', function ($scope, $http, $stateParams) {
  $scope.testing="testdata"
});

或者你可以从配置函数中删除[]

app.config(function ($stateProvider, $urlRouterProvider) {
 ...
}):

【讨论】:

  • 基于他得到'Cannot read property 'state' of undefined'的错误,这就是问题所在。只需从配置函数定义中删除[]。关于url问题,这是基于配置的第二个问题,但这不是问题。
猜你喜欢
  • 1970-01-01
  • 2020-05-09
  • 2018-12-04
  • 2019-11-16
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
相关资源
最近更新 更多