Reputation: 143
I can't understand why I can't access to $scope properties from the directive, the documentation says that directives doesn't create new scopes, so why can't I acess the $scope properties?
at app.js
'use strict';
var climbingApp = angular.module('climbingApp', []);
climbingApp.controller('ctrl', function($scope) {
$scope.initLocation = {
lat: -54.798112,
lng: -68.303375
};
at google-map.js
'use strict';
climbingApp.directive('gmap', function() {
return {
restrict: 'E',
replace: true,
template: '<div id="map-canvas"></div>',
link: function(scope, iElement, attrs) {
console.log(scope.initLocation);
},
}
})
at index.html
<html ng-app="climbingApp">
<body>
<gmap></gmap>
</body>
</html>
<script src="//code.angularjs.org/1.2.0-rc.2/angular.min.js"></script>
<script src="app/app.js"></script>
<script src="app/dependencies/google-maps.js"></script>
The console.log
always returns undefined.
Upvotes: 0
Views: 521
Reputation: 50395
You have to associate the controller with the view (if you use ngRoute
) or an element using ng-controller
. Something like this:
<body ng-controller="ctrl">...</body>
Upvotes: 1
Reputation: 7729
Inject the $scope in your controller like that :
var climbingApp = angular.module('climbingApp', ['ngRoute']);
climbingApp.controller('ctrl', function($scope) {
$scope.initLocation = {
lat: -54.798112,
lng: -68.303375
};
$scope.markers = [
{
'title' : 'prueba',
'position' : [-54.798112, -68.303375]
},
{
'title': 'prueba',
'position': [-54.798212, -68.303375]
}
];
});
'use strict';
climbingApp.directive('gmap', function() {
return {
restrict: 'E',
replace: true,
template: '<div id="map-canvas"></div>',
link: function(scope, iElement, attrs) {
console.log(scope.initLocation);
},
}
})
working plunkr here : http://plnkr.co/edit/fiK5viToLOVGobnAKZtB?p=preview
The log appears.
$scope or $location have to be pass in the function of your controller as param.
Upvotes: 0
Reputation: 104795
You need to inject the scope into the controller
climbingApp.controller('ctrl', function($scope) {
Upvotes: 2