AngularJS基于URL将不同的数据加载到同一部分

AngularJS基于URL将不同的数据加载到同一部分,angularjs,Angularjs,我现在的问题是找不到合适的问题来提问。 我想使用单个分部,并根据url使用不同的数据填充它。url看起来像这样 localhost:8080/#/users/USER_ID <div ng-repeat="item in showList"> <p>{{item}}</p> </div> 其中,users指向用户配置文件部分,相应的控制器,user\u ID将被发送到HTTP请求,以检索用户数据,然后填充用户配置文件部分 非常感谢任何解决这个问

我现在的问题是找不到合适的问题来提问。 我想使用单个分部,并根据url使用不同的数据填充它。url看起来像这样

localhost:8080/#/users/USER_ID
<div ng-repeat="item in showList">
<p>{{item}}</p>
</div>
其中,
users
指向用户配置文件部分,相应的控制器,
user\u ID
将被发送到HTTP请求,以检索用户数据,然后填充用户配置文件部分


非常感谢任何解决这个问题的方法。

好的,我可能会这样做。首先,我建议使用Ui路由器,而不是ngRoute。例如,它允许您创建自己的状态

$stateProvider

  // setup an abstract state for the tabs directive
    .state('A', {
        params: [A,B,C,D,E],
        url: "/A",
        templateUrl: "templates/YourView.html",
        controller: "YourController"
      })

    .state('B', {
        params: [F,G,H,I,J],
        url: "/B",
        templateUrl: "templates/YourView.html",
        controller: "YourController"
      })
基本上,这表示当您的Url是“/A”时,您的控制器使用,并且使用YourView.html,因此如果我理解正确,您有一个视图,希望根据Url显示不同的数据。通过将
'ui.router'
注入模块和
$state
注入控制器,您可以访问
$state.current.params

示例控制器

.controller('ExampleController', ['$rootScope', '$scope', '$state', function ($rootScope, $scope, $state){
//Here you get your params
//This will return you either [A,B,C,D,E] or [F,G,H,I,J] depending if Url is /A or /B

      $scope.showList = $state.current.params;

//Another Possibility with this is to listen for a StateChange

      $scope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) { 

//Here you can access all Params from the state you just left to the state you are going

});


}]);
现在您可以在YourView.html中这样显示它

localhost:8080/#/users/USER_ID
<div ng-repeat="item in showList">
<p>{{item}}</p>
</div>

{{item}}

因此,如果你在/A,列表显示A,B,C,D,E,如果你在/B,它显示F,G,H,I,J

如果您正在使用我极力推荐的:

$stateProvider
      .state('users', {
      url:'/users/:userId',
      templateUrl: 'user.html',
      controller:'UserCtrl'
  })
然后,您可以访问控制器中的
用户ID

App.controller('UserCtrl', ['$scope', '$stateParams', '$state', 'User', function($scope, $stateParams, $state, User) {
'use strict';
/* controller code */

    var req = User.$find($stateParams.userId);

}]);

当我使用
用户时,我还使用它对api进行HTTP调用。$find(id)

我找到了一个比我预期的更直接的解决方案

app.js

    $routeProvider.
    when('/user/:id', {
        templateUrl: 'user.html',
        controller: 'userController'
    });

然后在
userController
的实现中,
$routeParams
可用于从url检索
id
的值。

检查ngRoute:Thank you@dfsq,这让我找到了一个非常直接的解决方案,我在下面发布了这个解决方案!非常感谢。这正是我想要的。谢谢你的回答!我真的很感谢你花时间写这篇文章,我从你的回答中学到了一些新的东西。对不起,我的问题没有说得那么清楚。我希望实现的是有N个可能的URL来自…/users/其中N是注册用户的数量,用户ID用于通过HTTP获取用户数据以填充部分URL。