1

I have a webpage with a very simple structure, imagine left navigation, header bar and content area. If I have to describe it with code it looks like this

<body>
<aside ng-controller="SideNavCtrl">Left Nav data</aside>
<header ng-controller="HeaderCtrl">Page Title</header>
<section>
    <article ng-view>Page Content</article>
</section>

I'm using ngRoute and change my routes left and right. What I want is to update "Page Title" from the controller that accepted the route. I've tried hundreds of different ways but changing variable never forces header data update. Here's my latest variable share between controllers (which doesn't work)

app.controller("HeaderCtrl", ["$scope", "HeaderData", function($scope, HeaderData) {

        $scope.title = HeaderData.title();

    }]);

    app.factory("HeaderData", function() {

        var title = 'Default';

        return {
            title: function() { return title; },
            setTitle: function(newTitle) { title = newTitle; }
        }

    });

Later on in the routed controller I go like this

app.controller("PreviewBuildCtrl", ["$scope", "$routeParams", "$location", "BuildsAPIService", "HeaderData", function($scope, $routeParams, $location, BuildsAPIService, HeaderData) {

    $scope.build = BuildsAPIService.getBuildById($routeParams.buildId);

    HeaderData.setTitle("Previewing Build");

    console.log(HeaderData);

    if (!$scope.build) {
        $location.url('/builds/' + $routeParams.profession);
    }

}]);

The problem is that using HeaderData.setTitle() doesn't update the header contents. I really don't want to write jQuery code for this task. There must be a smarter, more angular way of doing this.

All I want to do is change the header title to "Page B" when you move to page b from page a and I consider adding breadcrumbs plugins an overkill for the task at hand :(

1 Answer 1

2

You break the data binding via title = newTitle. The controllers are pointing to the old title, but HeaderData is not pointing to it anymore so it is lost. You need another dot.

this.title = newTitle;

The title method should also return this.title, of course.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm getting "undefined" this way, regardless of the fact that PreviewBuildCtrl had just used setTitle
Whoop, fixed it. I pass the whole HeaderData to the scope now and just use those methods in the view. Updates accordingly now, thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.