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
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
.
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);
}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With