我有一个指令获取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 :(得分: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;
};
}
};
});
隔离范围:将一些值从父范围传递给指令
AngularJS提供了3种类型的前缀
- “@”(文本绑定/单向绑定)
- “=”(直接模型绑定/双向绑定)
- “&安培;” (行为绑定/方法绑定)
醇>所有这些前缀都接收来自指令元素属性的数据。
获取帮助
掌握AngularJS中指令的范围
http://www.undefinednull.com/2014/02/11/mastering-the-scope-of-a-directive-in-angularjs/
答案 1 :(得分:0)
为了使自定义指令更通用,我让它读取my-directive
属性的值并将该名称用作范围对象。
在这个例子中,我创建了两个框,&#34; boxA&#34;和&#34; boxB&#34;,并将它们的高度和宽度放在范围内。
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