Please I wanna know how to change the inside the dynamically in angularjs.
I'm using the NGresource and pulling json data from the back-end and i want to change it dynamically then i go to a new article for example.
Please I wanna know how to change the inside the dynamically in angularjs.
I'm using the NGresource and pulling json data from the back-end and i want to change it dynamically then i go to a new article for example.
You can change the HTML title and head elements on a per-view basis by using angularjs-viewhead.
here how to use it.
put the angularjs-viewhead.js in your asset folder
Declare as a dependency of your application as normal
var app = angular.module('myApp', ['ng', 'viewhead']);
This sort of setup can be achieved in an AngularJS application using the view-title directive. First, set up your title element to bind to the special scope variable viewTitle, which will be set when a tilted view is instantiated:
</title ng-bind-template="{{viewTitle}} - FooBaz">FooBaz</title>
<view-title>About</view-title>
Changing your title in JS is tricky when dealing with search engines as you may get curly braces in search results or the title for the page won't be right. However, if you have a rendering server for Google/Bing/Yahoo!, then it'll show up right when crawled. That, however, is another issue entirely. In order to do this, move your ng-app
directive to the html
attribute:
<html ng-app="myApp">
<head>
<title ng-bind="titleService.currentTitle">My Default Title</title>
</head>
<body>
<ng-view></ng-view>
</body>
</html>
Then create a service and bind it to the root scope:
angular.module('myApp')
.service('TitleService', function($location) {
var DEFAULT_TITLE = 'My Default Title';
return {
setTitle: function(title) {
this.currentTitle = title || DEFAULT_TITLE;
}
};
});
angular.module('myApp').run(function(TitleService, $rootScope) {
// This is mainly for a separation of concerns. These lines could
// easily go in the service definition.
$rootScope.$on('$locationChangeSuccess', TitleService.setTitle);
$rootScope.titleService = TitleService;
});
This assures that the default title will always be set by default. However, if you would like to set the title on a per-controller/directive basis you can do this inside of your code:
angular.module('myApp')
.controller('MainCtrl', function($scope, $location, TitleService, Article) {
// I'm just guessing what your logic might look like
var id = $location.search().articleId;
Article.get(id).then(function(article){
// Set the title however you want with article data
TitleService.setTitle(article.title);
});
});
EDIT: I moved a line to the run function to separate the concerns of the service from the concerns of the application.