Search code examples
angularjsangular-ui-routerangularjs-ng-resource

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


I have a webpage created on the angularjs in which I have used the ng-resource and the ui-router module.

In this app The main requirement I want is that in the navigation bar, I have created the ng-repeat="". which fetches the username from the database.

Now the navigation bar will be created

along with the ui-sref="{{username}}" and then now I have shown the app.js

this App.js is for the view which is going to be loaded and it will require the {{username}} as it id so here username is needed to dyanamically allocated for the each get request

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>


Solution

  • You are using ui-sref so I assume you are using ui-router?

    The argument in ui-sref is different from the normal href, you pass in the state name instead of the URL itself.

    For example your state is

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

    Then your sref will be ui-sref="main.user({userId: username})"