Eddy
Eddy

Reputation: 3703

Variable defined in controller not available in the html

I'm trying to access variables defined in my Angular Controller in an html file using this controller. But they're not there. Here's my code:

In MapsController:

angular.module('Maps').controller('MapsController', ['$scope', '$location', 'MapsService', function($scope, $location, MapsService) {

    $scope.number = 5; 
    ... ...
}]);

In Search.html:

<div class="generic-container" ng-controller="MapsController as ctrl">
    number: {{ctrl.number}}
</div>

When I run this, number is always empty. What am I missing?

(This is obviously a simplified version. In fact I'm trying to access an array that gets populated by the database. But it seems like in principal the idea is the same.)

Upvotes: 0

Views: 60

Answers (2)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

Using contoller as syntax (MapsController as ctrl) you tell angular to assign the controller instance to scope's variable ctrl. So add you property number to the controller instead of scope. Change $scope.number = 5; to this.number = 5; and it will work.

Upvotes: 2

Umair Farooq
Umair Farooq

Reputation: 1704

You are using the controller wrong in html

<div class="generic-container" ng-controller="MapsController as ctrl">
    number: {{ctrl.number}}
</div>

this will not work because you don't need to create an alias for a Controller in html.

<div class="generic-container" ng-controller="MapsController">
    number: {{ctrl.number}}
</div>

Also to access any variable in the scope of controller, you don't need to specify the controller object to access it.

<div class="generic-container" ng-controller="MapsController">
     number: {{number}}
</div>

it should do the job.

Upvotes: 1

Related Questions