Agape Agape - 3 months ago 14
Javascript Question

Angularjs ngroute data does not on second page

Okay, I'm new to Angular and to test the skills I got on Codecademy, I'm doing a test site of music artists. The first page is a list of artists. When you click on one of the artists' blocks, it loads the artist's info on the same page. For what ever reason, the first page handles fine, but the second page is the problem.

The template loads alright (since you can scope the styled elements of the page), but the data doesn't go through. It's, for the most part, blank.

I've tried everything I can think of, but I can't get this egg to crack. If you guys can help, I will be super mega ├╝ber greatful! There are a couple of snippets below, but the whole thing's here on plunker: https://plnkr.co/edit/67DAyg8ApyNYgVwvvlyw?p=info

HTML:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-resource.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js" type="text/javascript"></script>
</head>

<body>
<div class="main">
<div class="container">
<div ng-view></div>
</div>
</div>
<!-- Modules -->
<script src="app.js" type="text/javascript"></script>
<!-- Controllers -->
<script src="ArtistController.js" type="text/javascript"></script>
</body>


Javascript:

var app = angular.module('FavArtistsApp', ['ngRoute']);

app.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/', {templateUrl: 'Mural.html', controller: 'ArtistController'})
$routeProvider.when('/:artistsId', {templateUrl: 'Artist.html', controller: 'ArtistController'});
$routeProvider.otherwise({redirectTo: '/'});
}]);

Answer

To achieve expected result , use below

  1. Capture the route param- index using $routeParams.

    app.controller('ArtistController', ['$scope','$routeParams', function($scope,$routeParams)

  2. Use that index and get the selected object by using below

    $scope.currentArtist = $scope.artists[$routeParams.artistsId]

  3. Use that selected scope object and display it on second page

    <a class="button back" href="#/">Back</a>
    
    <h2 class="artist-name">{{currentArtist.name}}</h2>
    <p class="debut">Their debut album dropped in {{currentArtist.debutYear}}</p>
    <p class="album">Favorite album:<br/>
        <img ng-src="{{currentArtist.albumCover}}" height="300" width="300"/><br/>
    {{currentArtist.favoriteAlbum}}</p>
    <div>
        <iframe width="560" height="315" ng-src="{{currentArtist.track}}" frameborder="0" allowfullscreen></iframe>
    </div>
    <p class="bio">{{currentArtist.bio}}</p>
    

https://plnkr.co/edit/YxvCZUoaCn40vu9jEH6j?p=preview