简体   繁体   中英

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, ie 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?

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: '='
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM