我在這裏遇到的問題無法找到正確的問題。 我想使用單個部分,並使用基於url的不同數據填充它。 URL可能看起來像這樣AngularJS根據URL將不同的數據加載到相同的部分
localhost:8080/#/users/USER_ID
凡users
引導到用戶配置文件的部分,以及相應的控制器,並USER_ID
將在被髮送到一個HTTP請求來檢索用戶數據,然後將填充的用戶配置文件的部分。
解決這個問題的任何方向都非常感謝。
我在這裏遇到的問題無法找到正確的問題。 我想使用單個部分,並使用基於url的不同數據填充它。 URL可能看起來像這樣AngularJS根據URL將不同的數據加載到相同的部分
localhost:8080/#/users/USER_ID
凡users
引導到用戶配置文件的部分,以及相應的控制器,並USER_ID
將在被髮送到一個HTTP請求來檢索用戶數據,然後將填充的用戶配置文件的部分。
解決這個問題的任何方向都非常感謝。
如果您正在使用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);
}]);
我也是用angular-rest-mod進行HTTP調用,當我做User.$find(id)
謝謝!這正是我所期待的。 – James
好吧,我可能會這樣。首先,我會建議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」的「YourController」的使用和使用YourView.html所以如果我理解正確的,你必須要表現出不同的數據取決於Url.By注入'ui.router'
到您的模塊和$state
到您的控制器1個視圖,您可以訪問$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>
因此,如果您在/ A列表中顯示A,B,C,d,E,如果你是在/ B也顯示F字符,G,H,I,J
我希望這是有幫助的
謝謝你的回答!我很感激你花時間寫這篇文章,並且我從你的答案中學到了一些新東西。對不起,我的問題沒有像原來那麼清楚。 我期望實現的是讓N個可能的URL來自.../users /,其中N是註冊用戶的數量,用戶ID用於通過HTTP獲取用戶數據以填充部分內容。 – James
我發現了一個解決方案,這是一個很多更直接的比我預想的API
app.js
$routeProvider.
when('/user/:id', {
templateUrl: 'user.html',
controller: 'userController'
});
然後在userController
實施,$routeParams
可以用來retriev e來自url的id
的值。
Check ngRoute:https://docs.angularjs.org/api/ngRoute – dfsq
謝謝@dfsq,這使我得到了一個非常直接的解決方案,我在下面發佈! – James