我需要使用$ http.get来获取控制器中的json文件:
module.controller 'SampleMapController', ($http, $scope) ->
$http.get('../../highcharts/mapdata/world.geo.json').
success (data) ->
$scope.mapData = data # works and logs out correctly
并将其传递给一个指令,该指令使用该json进行映射:
module.directive 'MapDirective', () ->
require: '?SampleMapController'
templateUrl: '../template.html'
link: ($scope) ->
console.log $scope.mapData # undefined
$scope.$watch 'an.object.that.contains.more.data',
(newValue) ->
chart = new Highcharts.Chart({
chart: {
renderTo: 'container div'
}
# ... use $scope.mapData somewhere in here to render the global map
})
true
但是我没有运气访问那个$ scope,也不确定我是否应该将它放在$ rootScope上,或者事件需要控制器。
我在link:
我正在寻找的详细解释是在抽象的JSBin中。
答案 0 :(得分:2)
您可以将范围传递给指令。在你的dicrective中使用scope
键。以下是更多文档的链接:https://docs.angularjs.org/api/ng/service/$compile#-scope-
<强>指令强>
// ...
return {
require: '?SampleMapController',
restrcit: 'A', // Attribute
templateUrl: '../template.html',
scope: {
mapData: '=' // Bidirectionnal binding with the controller scope.
},
link: function( scope, elm, attrs ) {
scope.$watch( 'mapData', function(newValue) {
console.log( newValue );
// ...
});
};
// ...
<强> HTML 强>
<!-- ... -->
<div data-map-directive data-map-data="mapData"></div>
<!-- ... -->
答案 1 :(得分:1)
你不能在指令中注入$ scope,而是可以在指令
中传递链接函数中的作用域 your should use this :
link:function(scope,element,attributes){ // Notice to the function scope
// Now you have access to the scope , and you can do whaterver you want .
}
注意强> 在依赖注入理念中,在你的控制器中你可以注入$ scope作为依赖,而 $ 符号在angularJS中是已知的。另一个是,控制器中的依赖注入不遵循任何顺序,我的意思是 考虑一下:
app.controller('YouController',function($scope,$location,$http,...){
// You see in the injection , I injected $scope first , but it doesn't matter , I mean I can inject $location first , and then $scope , and ...
// So there is no order here !
// your stuff here
});
但是在指令中,将依赖关系传递给链接函数的顺序是重要的,另一方面,名称并不重要!
app.directive('yourdirective',function(){// you cannot inject $scope here !
return {
link : function(scope,element,attributes){// order is important
// anything that comes first , is scope
// Second is always element
// Third is always attributes
// So you could do this :
// function(scooooope,elem,att)
// See I changed the names , because here names are not important , but the order is important
}
}
});
修改:清除您的代码::(
module.directive('MapDirective',function(){
return{
require: '?SampleMapController'
templateUrl: '../template.html'
link: function(scope){
console.log scope.mapData
// Please test , if still undefiend ;
}
}
})