Search code examples
angularjsnode.jsngresource

ngresource open item in new page


I created a Rest API in Nodejs and Angular.

In my Angular app i got:

app.factory('User', function($resource) {
  return $resource('/api/users/:id', { id: '@_id' });
});


app.controller("myctrl", function($scope, $http, UserService, $location ){
    $scope.users = User.query();
       $scope.getData = function(userID){
          $location.absUrl("/api/students/"+userID);
       }
  });

In nodejs :

app.use('/api', require('./routes/api'));

I am able to list all the required information. Now i want to have the user opened in a new page. So when I click the user, i have:

EDIT:

<base href="/">  //in my html head
<p><ng-click="getData(user.id)">username</p>

When clicked on username, nothing happens. No error in console log also.

EDIT

$location.url("/api/students/"+userID); puts the proper location in the address bar but the page stays the same. So I used

$window.location.assign("/api/students/"+userID);

I'm not sure if I should be using $window.location.assign. This works and I get all the proper details. The only problem now is that its all in JSON. How and where do I use angular {{}} to show the data? Plus I also want to add some custom html in that output.

thanks.


Solution

  • you can use target blank in your a tag. In addition to that you will need to inject $location or just use window.location to get the full path, otheriwse the link won't work.

    So long story short:

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope, $location) {
      
      $scope.userID = 10;
      $scope.baseUrl = $location.protocol() + "://" + $location.host() + ":" + $location.port();
      
      $scope.fullUrl = $scope.baseUrl + '/api/students/' +  $scope.userID;
      
      
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="plunker">
      <div ng-controller="MainCtrl">
        <p>Hello!</p>
        
        <a target="_blank" href="{{baseUrl + '/api/students/' +  userID}}" >Go to new window</a>
        <br/>
        <a target="_blank" href="{{fullUrl}}" >Go to new window</a>
      </div>
    
    </div>

    And a plunker just in case.