2015-12-03 71 views
1

我有一个指令,它获取div的高度和宽度,我希望在控制器中传递这些数据。如何才能做到这一点?将数据从指令传递到控制器

angular.module('Module', []) 
    .controller('TestController', ['$scope', '$rootScope', 
     function($scope, $rootScope,) { 



    }]).directive('myDirective', function($timeout) { 
     return { 
      restrict: 'A', 

      link: function(scope, element, attrs) { 
       scope.height = element.prop('offsetHeight'); 
       scope.width = element.prop('offsetWidth'); 
      } 
     }; 
    }); 

回答

0

HTML:

<input type="text" your-custom-text-field ng-model="textValue" ng-tooltip-max="5"> 

指令:

yourApp.directive('yourDirName', function() { 
    return { 
     restrict: 'E', 
     scope: { 
      'ngToolTipMax': '&', 
      'ngModel': '&' 
     }, 
     link: function (scope, element, attrs) { 
      scope.onChange = function() { 
       scope.ngModelValue = scope.model; 
      }; 
     } 
    }; 
}); 

隔离范围:从PA传递一些值租范围的指令

是有3种类型的前缀AngularJS提供

  1. “@”(Text绑定/单向绑定)
  2. “=”(直接模型绑定/双向结合)
  3. “&”(行为结合/方法结合)

所有这些前缀从指令元素的属性接收数据。从http://jsfiddle.net/shidhincr/pJLT8/10/light/

掌握指令的AngularJS

http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/

+0

这并不说明我可以从指令传递这个数据到父范围。 – nareeboy

0

范围,以使自定义指令更加灵活

得到帮助,我把它读my-directive属性的值和使用该名称作为范围对象。

在此示例中,我创建了两个框“boxA”和“boxB”,并将其高度和宽度放在范围上。

HTML

<body ng-app="myApp"> 
<pre> 
green box size = {{boxA.height}},{{boxA.width}} 
red box size = {{boxB.height}},{{boxB.width}} 
</pre> 
    <div my-directive="boxA" style="height:50px;width:100px;background:green"> 
    </div> 
    <div my-directive="boxB" style="height:80px;width:20px;background:red"> 
    </div> 
</body> 

JS

angular.module("myApp").directive('myDirective', function() { 
    return { 
      restrict: 'A', 
      link: function(scope, element, attr) { 
        scope[attr.myDirective] = {}; 
        var d = scope[attr.myDirective]; 
        d.height = element.prop('offsetHeight'); 
        d.width = element.prop('offsetWidth'); 
        console.log(scope); 
        } 
    }; 
}); 

结果

green box size = 50,100 
red box size = 80,20 

The Plunker

相关问题