[英]AngularJs share $scope between controller and controller
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? 我不明白为什么我不能从指令访问$ scope属性,文档说指令不能创建新的作用域,所以为什么我不能访问$ scope属性?
at app.js 在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 在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 在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. console.log
始终返回未定义。
您需要将范围注入控制器
climbingApp.controller('ctrl', function($scope) {
You have to associate the controller with the view (if you use ngRoute
) or an element using ng-controller
. 您必须将控制器与视图(如果使用ngRoute
)或使用ng-controller
的元素相关联。 Something like this: 像这样:
<body ng-controller="ctrl">...</body>
Inject the $scope in your controller like that : 像这样在控制器中注入$ scope:
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 在这里工作的plunkr: 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. $ scope或$ location必须作为参数传递给控制器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.