javascript - $routeParams 未填充

标签 javascript angularjs

有些我是路由和单页 Web 应用程序的新手,但我一直在努力正确学习 Angular。然而我遇到了一些麻烦和一些奇怪的问题。我遵循了构建目录的指南,我的目录如下所示:

app/
    components/
        profile/
            profile.html
            ProfileModel.js
            ProfileController.js
            ProfileFactory.js
    app.module.js
    app.routes.js

我的主模块位于 app.module.js 中,并使用 ngRouteprofile.app (配置文件的模块)注入(inject)依赖项从 ProfileModel.js 查看)。它的声明如下:

angular
    .module('app', ['ngRoute', 'profile.app'])
    .controller('MainController', MainController);

function MainController() {
    this.message = 'This is the home page';
}

然后在我的 app.routes.js 文件中,我声明了应用程序所需的所有路由(到目前为止只有一个,即配置文件):

angular
    .module('app')
    .config(routeConfig);

routeConfig.$inject = ['$locationProvider', '$routeProvider'];

function routeConfig ($locationProvider, $routeProvider) {
    $routeProvider
        .when('/user/:user_id', {
                templateUrl: '/app/components/profile/profile.html',
                controller: 'ProfileController',
                controllerAs: 'profile'
            }
        )
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
}

这是我的ProfileController.js:

angular
    .module('app.profile')
    .controller('ProfileController', ProfileController);

ProfileController.$inject = ['ProfileFactory', '$routeParams'];

function ProfileController(ProfileFactory, $routeParams) {
    var vm = this;

    vm.user_id = $routeParams.user;

    console.log($routeParams.user_id);
    vm = ProfileFactory.userProfile(vm.user_id); //Gets the profile of the user and sets to to vm


}

所以我有两个主要问题。尽管我在 app.routes.js 中定义了路由,但 $routeParams.user_id 被记录为空。这很奇怪,因为我的 index.html (包含每个 .js 文件的 HTML 文件)中有一个 ng-view 指令。这意味着一旦 Controller 及其依赖项被实例化,我应该可以立即访问路由参数。但是,当我转到http://example.com/user/1时,我没有记录任何内容(未定义)。

我的第二个问题是我将 ngRoute 作为依赖项包含在 profile.app 和我的主模块中(其中 profile.app 是依赖性)。但是,我后来从 profile.app 中删除了 ngRoute 作为依赖项,但我在 ProfileController< 中留下了 $routeParams 的注入(inject) 和 AngularJS 根本没有提示。这看起来很奇怪,因为依赖关系不再明确存在于 profile.app 中。那么为什么我仍然可以注入(inject) $routeParams 尽管我的 profile.app 模块中没有 ngRoute 呢?是因为它从主模块获取ngRoute吗?

最佳答案

我认为问题在于您将 controllerAs 设置为“profile”,但随后在 Controller 中编写 var vm = this;

这两个必须相同,以便您可以编写 controllerAs: 'vm'var profile = this;

关于javascript - $routeParams 未填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071927/

相关文章:

angularjs - 将 d3 时间线与 Angular 结合使用

angularjs - 开发angular js应用的好工具有哪些?

javascript - 多个文本框输入验证检查

javascript - 使用 HTML 的用户输入列表加上处理信息的方法

javascript - 在 jquery 中检索数据属性 - 错误

需要 JavaScript、J Query 帮助,如何对跨度值求和,如下面的 HTML 所示

用于 WebStorm 的 AngularJS 插件

javascript - QWebView无法显示通过javascript设置的外部图片内容 $ ("#<node_name>".html(<html_content>)

php - 如何确保AJAX被JavaScript调用?

angularjs - 关闭AngularJS中所有打开的 Bootstrap 模式?