Eddy Eddy - 3 months ago 13
AngularJS Question

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.)

Answer

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.

Comments