rockey dsouza rockey dsouza - 3 months ago 17
Javascript Question

Change Page Title Dynamically AngularJS

Below is my code,
i need to change the maintitle dynamically in h2 tag on click of navigation (navlinks) through angularJS.

Thanks in advance..



var portfolioApp = angular.module('portfolioApp', []);

portfolioApp.controller('navCtrl', ['$scope', '$location', function ($scope, $location) {

$scope.navLinks = [{
Title: 'home',
LinkText: 'Home'
}, {
Title: 'about',
LinkText: 'About Us'
}, {
Title: 'portfolio',
LinkText: 'Portfolio'
}, {
Title: 'contact',
LinkText: 'Contact Us'
}];

$scope.navClass = function (page) {
var currentRoute = $location.path().substring(1) || 'home';
return page === currentRoute ? 'active' : '';
};

}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<div ng-app="portfolioApp">
<h2>{{maintitle}}</h2>
<header class="well sidebar-nav">
<ul class="nav nav-list" ng-controller="navCtrl">
<li ng-repeat="navLink in navLinks" ng-class="navClass('{{navLink.Title}}')">
<a href='#/{{navLink.Title}}'>{{navLink.LinkText}}</a>
</li>
</ul>
</header>
</div>




Answer

Check Out This:

var portfolioApp = angular.module('portfolioApp', []);   

portfolioApp.controller('navCtrl', ['$scope', '$location', function ($scope, $location) {
$scope.maintitle = "Some Thing";
    $scope.navLinks = [{
        Title: 'home',
        LinkText: 'Home'
    }, {
        Title: 'about',
        LinkText: 'About Us'
    }, {
        Title: 'portfolio',
        LinkText: 'Portfolio'
    }, {
        Title: 'contact',
        LinkText: 'Contact Us'
    }];

    $scope.navClass = function (page) {
        var currentRoute = $location.path().substring(1) || 'home';
        return page === currentRoute ? 'active' : '';
    };
  $scope.goToLink = function(navlink){
    $scope.maintitle = navlink.Title;
    // fix location service accordin to your requirment
    $location.path(navlink.Title);
  }

}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.3/angular.min.js"></script>
<div ng-app="portfolioApp">
<header class="well sidebar-nav">
    <ul class="nav nav-list" ng-controller="navCtrl">
      <h2>{{maintitle}}</h2>

        <li ng-repeat="navLink in navLinks" ng-class="navClass('{{navLink.Title}}')">
            <a ng-click="goToLink(navLink)">{{navLink.LinkText}}</a> 
        </li>
    </ul>
</header>
  </div>