E
E
Evgeniy Samoilenko2015-08-25 21:03:32
Angular
Evgeniy Samoilenko, 2015-08-25 21:03:32

How to use $scope outside of controller?

I am learning angularjs, and I got up on such a seemingly banal thing:
Here I have a siteContent module, I declare it like this:

<!DOCTYPE html>
<html lang="ru" ng-app="siteContent">
<head >
    ....
</head>
<body>
    <ng-view></ng-view>
</body>
</html>

In the module, with the help of $routeProvider, I have navigation, everything is fine with this, with the help of rest I get data from the database, everything is ok, inside ng-view I use templates, there are no problems with this either. But here's the thing, since I'm making a simple site, I need to change both the title and description and so on when changing pages, but I don't understand how, because in fact they are outside the controller. How to be?
I studied the example with the phone cat application far and wide, but there is not a word about this, maybe there are some other examples or anything at all. I found the right question in the search How to change the title and meta tags in the head in AngularJS? However, I didn't understand how it could help.
Please help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Kononenko, 2015-08-25
@samoilenkoevgeniy

Get yourself some kind of service, for example Page, which will contain all the information related to the page in general, such as the current menu item, title, and so on.

app.service('Page', [function () {
  var Page = this;
}]);

Inside app.run just put this service in $rootScope:
app.run(['$rootScope', 'Page', function ($rootScope, Page) {
  $rootScope.Page = Page;
}])

Now just inject this service into any controller and install whatever your heart desires.
app.controller('MyCtrl', ['$scope', 'Page', function ($scope, Page) {
  Page.myVar = 'lol';
}])

In the Angular templating engine will be available as {{Page.myVar}} or more strictly {{$root.Page.myVar}}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question