0

I got an index.html page with the following code

<html>
<head>
<title>{{title}}</title>
</head>
</html>

And i got a view.html

<div ng-controller="changeCtrl">
<input type="text" ng-model="page-title">
</div>

The routing works perfectly,

Now how can i bind the page-title model to the {{title}} while i type?

Thanks

user3052526
  • 681
  • 10
  • 24

3 Answers3

4

To avoid using $rootScope or moving ng-app, use a service to handle setting the page title. In the snippet below I've given an example of using a service.

angular.module('app', [])

.service('PageService', function($window) {
    return {
       setTitle: function (newTitle) { $window.document.title = newTitle; }
    };
})

.controller('ChangeCtrl', function(PageService) {
    this.setPageTitle = PageService.setTitle;
});
<html>
    <head>
        <title>My Awesome App</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    </head>
    <body ng-app="app">
        <div ng-controller="ChangeCtrl as ctrl">
            <label>{{ctrl.title}}</label>
            <input type="text" ng-model="ctrl.title" ng-change="ctrl.setPageTitle(ctrl.title)">
        </div>
    </body>
</html>
digitil
  • 879
  • 5
  • 11
1

First of all, since the expression is right under the html root element, the angular application must "cover" this element. So ng-app should be on the html element:

<html ng-app="app">

Second, since the expression is outside of any controller scope, angular looks for the title field in the $rootScope. So, you need your input field, inside a view handled by a controller, to modify the value of a $rootScope attribute.

That can't be done:

<input ng-model="title" />

will set the field titleon the controller scope. What can be done, though, is to access an object, by scope inheritance, defined in the root scope, and modify one of its attributes. So, firstmake sure such an object exists in the root scope:

angular.module('app').run(function($rootScope) {
    $rootScope.page = {
        title: 'default title'
    };
});

Then change the expressions to access the title attribute of this object:

<title>{{ page.title }}</title>

and in the controller view:

<input ng-model="page.title" />
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • That was my original solution till i read that using the $rootScope is frowned upon. But the solution works perfectly. – user3052526 Oct 17 '15 at 06:13
0

make all your data bindings inside ng-controllers scope, that is {{title}} should inside or you move to your ng-controller to html tag, :)

Sarath
  • 126
  • 1
  • 7