Angularjs 将$http从控制器传递到指令
我需要使用$http.get在控制器中获取json文件:Angularjs 将$http从控制器传递到指令,angularjs,coffeescript,angularjs-scope,angularjs-http,Angularjs,Coffeescript,Angularjs Scope,Angularjs Http,我需要使用$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 并将其传递
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上,或者事件需要控制器
我正在链接中生成一个高图表图:
我要查找的内容的详细解释在摘要中。您不能在指令中注入$scope,而是可以在指令中的链接函数中传递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
}
}
});
编辑:清除代码::(
您可以将作用域传递给指令。通过在DIRECTIVE中使用
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>
<!-- ... -->
是$scope和scope不是一回事吗?那么我的示例就可以运行了,但事实并非如此。它必须涉及$http项。兄弟,我真的不知道你有什么问题。你说$scope在你的指令中没有定义,我说你应该在所有指令中使用scope,而不是$scope。还有什么问题吗?这很有帮助,但是需要重新研究使用$http获取JSON响应,直到将该响应注入到指令中为止。感谢您的帮助。我添加了一个jsBin示例,说明了我正在尝试做的事情:带有作用域的链接函数。$watch explaution有点帮助,但在使代码正常工作时仍然存在问题。
<!-- ... -->
<div data-map-directive data-map-data="mapData"></div>
<!-- ... -->