geekchic
geekchic

Reputation: 2431

Passing variable from directive to controller in AngularJS

So I have an nvd3 graph in my index.html whose height is set to {{varyingHeight}} like so (code snippet):

<nvd3-line-plus-bar-chart data="data"
           showXAxis="true" showYAxis="true"
           tooltips="true" interactive="true"
           showLegend="true"
           height='{{varyingHeight}}'
           >
 </nvd3-line-plus-bar-chart>

Now in my directive, I have a code which identifies when the height change takes place, and what the new height is:

app.directive('test', function () {
 return {
 restrict: 'EA',
 scope: {},
 link: function (scope, element) {
   scope.$on('split.resize', function() {
     console.log('I got resized');
     console.log(element.height());
    });    
  }
       };
  });

In my controller, I now want to be able to set the new height like so:

$scope.$apply(function(){
   $scope.varyingHeight = h;  
})

I'm new to angularjs so I can't figure what the best way is to do this. I have seen answers which show how to do this the other way round, i.e from the controller to the directive but this hasn't helped me. How do I pass a element.height() to variable h from the directive to the controller? Or is my code structured wrong in the first place?

Upvotes: 0

Views: 441

Answers (2)

User4567
User4567

Reputation: 1025

I also faced this issue, I resolved it by passing the height as attribute to the directive

My sample directive

App.directive('aBc',function () {
return {
    restrict : 'AE',
    scope : {
        gridHeight : '@'
    },
    template : '<div style= "height : {{gridHeight}}px" >'
        +'<p>sdtyhdrtydrt--  {{gridHeight}} </p>'
        + '</div>'
};

});

pass the height through directive tag

directly you can pass the height

<div a-bc grid-height="200"></div>
<div a-bc grid-height="500"></div>
<div a-bc grid-height="1000"></div>

or you can set it from your controller

<div a-bc grid-height="someHeight"></div>

initialize someHeight in controller like

$scope.someHeight = 500;

Upvotes: 0

Anders Ekdahl
Anders Ekdahl

Reputation: 22933

You do it by binding the height attribute to the value passed from the controllers scope. Here's an example: http://jsbin.com/vapipizu/1/edit

The important part is that you replace height="{{varyingHeight}}" with height="varyingHeight" and that your directive binds the height attribute like this:

scope: {
  height: '='
}

Upvotes: 1

Related Questions