6

I am starting to build my first single page application in AngularJS and am stuck on a simple problem. I want to be able to set scope variables 'title' and 'subtitle' to change the page header each time a user clicks a 'link'. On the main index page, the html where it should be displaying looks like this:

<div id="header">
    <h1>{{title}}</h1>
    <h3>{{subtitle}}</h3>
</div>

In the app.js file where I am doing all of my routing, I have multiple controllers that get applied depending on the url. Each of the controllers looks something like this:

app.controller('displayCtrl', function($scope, $http) {
    $scope.title = "Machine Profiles";
    $scope.subtitle = "Add, remove, and view data about machines";
    console.log($scope.title);
});

As you can see I am outputting to the console the variable that I just set, and it actually is displaying the correct thing. The problem is that the h1 and h3 tags are not displaying the scope variable! My title and subtitle in the header are blank, even though the scope variable is being set and logged. I am not getting any errors in the console on page load or when I click the links. The 'templateUrl' that I am loading in the routeProvider is displaying the content on all of the partial pages in the main container as well. JUST THE TITLES ARE BROKEN. Please help. Thanks in advance

1
  • Did you add ng-controller="displayCtrl" to your element? Commented May 30, 2014 at 1:12

2 Answers 2

7

Is <div id="header"> outside of your ng-view?

If it is - that means that <div id="header"> is outside of displayCtrl's scope.

Try updating $rootScope instead of $scope.

app.controller('displayCtrl', function($scope, $rootScope, $http) {
    $rootScope.title = "Machine Profiles";
    $rootScope.subtitle = "Add, remove, and view data about machines";   
});

Make sure that <div id="header"> is inside ng-app.

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

1 Comment

Thanks, it was adding rootScope that did it. In my mind, $scope was for the ng-app from top to bottom, but I guess it means just within the ng-view?
1

Please make sure that you have bound angular to your html page .

Try looking at this example

You can also try reformatting the controller as follows. Angular recommends inline injection annotation

app.controller('displayCtrl', ['$scope','$http', function($scope, $http) {
    $scope.title = "Machine Profiles";
    $scope.subtitle = "Add, remove, and view data about machines";
    console.log($scope.title);
}]);

Comments

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.