Claudiu Creanga
Claudiu Creanga

Reputation: 8366

Link to #ID element from another page in AngularJS

I've tried all the solutions presented here: How to handle anchor hash linking in AngularJS

But none worked for me.

In my header.html I have a link: <a id="button" href="#/views/home#page"> Contact</a></li>

To an ID in home.html

When I am in /home it works, but when I am in another page it doesn't work.

I tried using ##page with no success. Or putting this in app.js:

app.run(function($rootScope, $location, $anchorScroll, $routeParams) {
  $rootScope.$on('$routeChangeSuccess', function(newRoute, oldRoute) {
    $location.hash($routeParams.scrollTo);
    $anchorScroll();  
  });
});

and customizing my link:

href="#/views/home/?scrollTo=page"

Can someone explain which files should I edit and how?

Edit: I started from Angular-Seed

My app.js is:

'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.training',
  'myApp.faq',
  'myApp.media',
  'myApp.contact',
  'myApp.home',
  'myApp.apply',
  'myApp.classes',
  'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/views/home'});
}]);

And in every view I have another js file like training.js which looks like:

'use strict';

angular.module('myApp.training', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/views/training', {
    templateUrl: 'views/training/training.html',
    controller: 'TrainingCtrl'
  });
}])

.controller('TrainingCtrl', [function() {

}]);

It is configured based on angular-seed model.

So, when, I am in view /faq that has the partial header with the menu and all the links, how can I link to a specific ID in view /home?

Upvotes: 2

Views: 1437

Answers (1)

Josep
Josep

Reputation: 13071

I think that the problem is that you have the logic for scrolling to that hash in the $routeChangeSuccess and as the documentation says, this event is:

Broadcasted after a route dependencies are resolved. ngView listens for the directive to instantiate the controller and render the view.

So the view is not rendered yet, therefore the DOM element with that id doesn't exist yet.

Try putting that logic in the onload event of the ngView directive instead.

I've created this plunker: http://plnkr.co/edit/S7bUT8iYY7UEti71X5Z8?p=preview that shows that if you add that logic into the onload event of the ngView directive everything works fine.

Upvotes: 1

Related Questions