简体   繁体   English

angular.js路由和stateparams

[英]angular.js routing and stateparams

I'm trying to modify standard user module of meanjs. 我正在尝试修改meanjs的标准用户模块。 I added a simple route: 我添加了一条简单的路线:

state('users', {
            url: '/users/:username',
            templateUrl: 'modules/users/views/view-profile.client.view.html'
        });

And in my view: 在我看来:

data-ng-controller="ViewProfileController" data-ng-init="findUser()"

I also injected $stateParams to my controller. 我还向控制器添加了$ stateParams。 So in my ViewProfileController - findUser function, when I write this: 所以在我的ViewProfileController - findUser功能,当我写这篇文章:

console.log($stateParams.username)

I expect to get username parameter. 我希望得到用户名参数。 But it returns undefined . 但是它返回undefined

When I set the route this way, 当我这样设定路线时

state('users', {
            url: '/users/:username',
            template: function ($stateParams){
                return $stateParams.username;
            }
        });

it returns username. 它返回用户名。 I don't know what is wrong or missing. 我不知道什么是错的或丢失的。 Any ideas? 有任何想法吗?

edit: this was my full controller code 编辑:这是我完整的控制器代码

'use strict';

angular.module('users').controller('ViewProfileController', ['$scope', '$http', '$stateParams', '$location', 'Users', 'Authentication', 
function($scope, $http, $location, Users, Authentication, $stateParams) {
    $scope.user = Authentication.user;


    $scope.findUser = function () {
        console.log($stateParams);
        ...
    };
}
]);

Your dependencies don't match up - the list of dependencies need to match the parameters in the controller function in the same order: 您的依赖项不匹配-依赖项列表需要以相同顺序匹配控制器函数中的参数:

'use strict'; 
angular.module('users')
.controller('ViewProfileController', ['$scope', '$http', '$stateParams', '$location', 'Users', 'Authentication', 
  function($scope, $http, $stateParams, $location, Users, Authentication) { 
    $scope.user = Authentication.user; 
    $scope.findUser = function () { 
      console.log($stateParams); 
    }; 
  }
]);

I should use controller instead of template. 我应该使用控制器而不是模板。

Replace into you code the template: to the follow snippet: 将代码template:替换为以下代码段:

controller: function($stateParams){
    console.log('username: '+$stateParams.username);
}

You can see a complete example of this feature here 您可以在此处查看此功能的完整示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM