AngularJS根据URL将不同的数据加载到相同的部分

时间:2015-09-02 05:08:09

标签: angularjs

我在这里遇到的问题是无法找到正确的问题。 我想使用单个部分,并使用基于网址的不同数据填充它。网址看起来像这样

localhost:8080/#/users/USER_ID

users指向用户配置文件partial,并且相应的控制器和USER_ID将被发送到HTTP请求以检索用户数据,然后填充用户配置文件部分。

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

3 个答案:

答案 0 :(得分:1)

如果您使用{强烈推荐的ui-router

$stateProvider
      .state('users', {
      url:'/users/:userId',
      templateUrl: 'user.html',
      controller:'UserCtrl'
  })

然后,您可以访问控制器中的userId

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

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

}]);

当我User.$find(id)

时,我也使用angular-rest-mod对api进行HTTP调用

答案 1 :(得分:1)

我发现了一个比我预期更直接的解决方案

app.js

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

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

答案 2 :(得分:0)

好的,所以我可能会这样。首先,我建议使用Ui-Router而不是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"
      })

基本上这表示当您的网址为“/ A”时,使用“YourController”并使用YourView.html,如果我理解正确您有1个视图,您希望显示不同的数据,具体取决于Url.By Injecting '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中显示这个

<div ng-repeat="item in showList">
<p>{{item}}</p>
</div>

所以如果您的at / A列表显示A,B,C,D,E,如果你在/ B,它显示F,G,H,I,J

我希望这很有用

相关问题