Monday, 15 September 2014

angularjs - Pass $http from Controller to Directive -



angularjs - Pass $http from Controller to Directive -

i need utilize $http.get grab json file in controller:

module.controller 'samplemapcontroller', ($http, $scope) -> $http.get('../../highcharts/mapdata/world.geo.json'). success (data) -> $scope.mapdata = info # works , logs out correctly

and pass directive, uses json mapping purposes:

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' } # ... utilize $scope.mapdata somewhere in here render global map }) true

but i'm not having luck accessing $scope, , not sure if should putting on $rootscope, or event require controller.

i'm generating high charts map within of link:

a detailed explanation of i'm looking in abstracted jsbin.

you cant inject $scope in directives , instead can pass scope in link function in directive

should utilize : link:function(scope,element,attributes){ // notice function scope // have access scope , , can whaterver want . }

note in dependency injection philosophy , in controller's can inject $scope dependency , , $ sign known in angularjs .and other thing , dependency injection in controllers not follow order , mean consider :

app.controller('youcontroller',function($scope,$location,$http,...){ // see in injection , injected $scope first , doesn't matter , mean can inject $location first , , $scope , , ... // there no order here ! // stuff here });

but in directives , order of passing dependencies link function is important, on other hand , names not of import !

app.directive('yourdirective',function(){// cannot inject $scope here ! homecoming { link : function(scope,element,attributes){// order of import // comes first , scope // sec element // 3rd attributes // : // function(scooooope,elem,att) // see changed names , because here names not of import , order of import } } });

edit : cleared code : :(

module.directive('mapdirective',function(){ return{ require: '?samplemapcontroller' templateurl: '../template.html' link: function(scope){ console.log scope.mapdata // please test , if still undefiend ; } } })

angularjs coffeescript angularjs-scope angularjs-http

No comments:

Post a Comment