Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope variable not printing AngularJS

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

like image 265
dge888 Avatar asked May 30 '14 00:05

dge888


2 Answers

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.

like image 61
thedude Avatar answered Oct 20 '22 00:10

thedude


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);
}]);
like image 45
v2saumb Avatar answered Oct 20 '22 00:10

v2saumb