[英]How to create a custom angular directive which contains multiple input controls?
I am working on my first angular project. 我正在做我的第一个有角度的项目。 For better or for worse, I am trying to convert almost all repeatable HTML into directives. 无论好坏,我都在尝试将几乎所有可重复的HTML转换为指令。 I have a requirement to let the user select a time in HH:MM format. 我要求用户选择HH:MM格式的时间。 So I need to show two SELECT elements. 因此,我需要显示两个SELECT元素。 Since I need to give this control at quite a few places, I am trying to convert into a directive. 由于我需要在很多地方提供此控件,因此我试图将其转换为指令。
<div class="filterLabel">{{fieldLabel}}</div>
<select class="FilterDDL" ng-style="{width: selectHhWidthPx + 'px'}">
<option value="none">HH</option>
<option value="8">08</option>
<option value="9">09</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
</select>
<span>:</span>
<select class="FilterDDL" ng-style="{width: selectHhWidthPx + 'px'}">
<option value="none">MM</option>
<option value="0">00</option>
<option value="30">30</option>
</select>
My expected end result from this directive is to obtain a time value in minutes [(HH * 60 + MM)] for further calculations. 我从该指令获得的最终结果是获得以分钟为单位的时间值[(HH * 60 + MM)],以进行进一步的计算。 However I can't think of a way in which I can get a single ngModel associated with my directive which returns the time in Minutes from the combination of two dropdowns. 但是我想不出一种方法来获取与指令关联的ngModel,该指令从两个下拉菜单的组合中返回以分钟为单位的时间。 I read about Link function but can't figure out if I can use it in my scenario. 我读到有关Link函数的信息,但无法弄清楚是否可以在我的方案中使用它。 Is it even a good practice to have custom directives span over multiple input elements? 让自定义指令跨越多个输入元素甚至是一种好习惯?
Please refer below code: 请参考以下代码:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="angular.min.js"></script>
<script type="text/javascript">
angular.module('demoApp', [])
.controller('Controller', ['$scope', function ($scope) {
$scope.totalMinutes = function () {
return $scope.mintutes + ($scope.hours * 60);
}
$scope.mintutes = 1;
$scope.hours = 1;
}])
.directive('timeSelection', function () {
return {
restrict: 'E',
template: "Hours:<input type='number' ng-model='hours' /> Minutes:<input type='number' ng-model='minutes' />",
scope: {
hours: "=hours",
minutes:"=mintutes"
}
};
});
</script>
</head>
<body>
<div ng-app="demoApp">
<div ng-controller="Controller">
<time-selection hours="hours" mintutes="mintutes" ></time-selection>
Total Minutes : {{totalMinutes()}}
</div>
</div>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.