[英]Pass Data from directive into controller
我有一個指令可以獲取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');
}
};
});
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/
為了使自定義指令更具通用性,我讓它讀取了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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.