在 ng-resource 中动态分配 URI 中的 id

dynamically allocate the id in the URI in the ng-resource

我在 angularjs 上创建了一个网页,我在其中使用了 ng-resource 和 ui-router 模块。

在这个应用程序中,我想要的主要要求uirement 是在导航栏中,我创建了 ng-repeat=""。从数据库中获取用户名。

现在将创建导航栏

连同 ui-sref="{{username}}" 然后现在我展示了 app.js

此 App.js 用于将要加载的视图,它将要求ui重新输入 {{username}} 作为它的 ID 所以这里需要为每个get请求动态分配用户名

var app = angular.module('trendy', ['ngResource']);

app.controller('trendyWho',[ 'UserFactory', function ( UserFactory) {

  var self=this;
  
    UserFactory.get({}, function (userFactory){
       self.userdata = userFactory.user;
       
    });
    
}]);
  


app.factory('UserFactory', function ($resource) {
   
    return $resource('Trending/js/{{id:username}}', {}, {
        query: {
            method: 'GET',
            params: {},
            isArray: true
        }
        
    })
    
 
});
<!-- index.html -->

<!DOCTYPE html>
<html ng-app="trendy">
<head>
<!-- CSS (load bootstrap) -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">  
<!-- JS (load angular, ui-router, and our custom js file) -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js" ></script>
<script src="app.js"></script>
</head>
<!-- apply our angular app to our site -->
<body >
<!-- NAVIGATION -->
<nav class="navbar navbar-inverse" role="navigation">
<div class="navbar-header">
  <a class="navbar-brand" ui-sref="#">AngularUI Router</a>
</div>
<ul class="nav navbar-nav" ng-repeat="">
   <li><a ui-sref=".../{{username}}">{{username}}</a></li>
   
</ul>
</nav>

<!-- MAIN CONTENT -->
<div class="container">

    <!-- THIS IS WHERE WE WILL INJECT OUR CONTENT ============================== -->
    <div ui-view></div>

</div>

</body>
</html>

您正在使用 ui-sref 所以我假设您正在使用 ui-路由器?

ui-sref中的参数不同于普通的href,你传入的是州名而不是URL本身。

例如你所在的州是

.state('main.user', {
    url: "/user/{userId:[0-9]{1,}",
    template: ...,
    controller: ...
})

那么你的sref将是 ui-sref="main.user({userId: username})"