【发布时间】:2018-05-29 15:18:48
【问题描述】:
我有一个指令函数scope.automaticallySelectClosingTime()。它采用第一个选择的下拉值的值,并在第二个选择的下拉列表中创建时间列表。它在ng-change 上触发。
指令:
.directive('closingTimeSync', function() {
return {
template: `<md-select ng-disabled="time.uiStoreOpen === false" ng-model="openCloseSet[1]">
<md-option ng-repeat="uiTime in closingTimes" ng-value="uiTime.msValue">
{{::uiTime.display}}
</md-option>
</md-select>`,
replace: true,
transclude: true,
link: function(scope) {
scope.automaticallySelectClosingTime = function(msValue) {
scope.closingTimes = scope.uiAvailableTimes;
var dayMS = 86400000 - 1;
var remainingTimings = [];
var index = scope.closingTimes.map(function(obj) {
return obj.msValue;
}).indexOf(msValue);
index = (index === scope.uiAvailableTimes.length - 1) ? 1 : index + 1;
scope.closingTimes = scope.closingTimes.slice(index, scope.uiAvailableTimes.length);
if (msValue !== dayMS) {
remainingTimings = scope.uiAvailableTimes.slice(1, index - 1);
}
scope.closingTimes = scope.closingTimes.concat(remainingTimings);
};
}
};
})
控制器。
.controller('TestCtrl', function($scope) {
init();
// CREATE AVAIABLE TIMES
$scope.uiAvailableTimes = [];
$scope.uiAvailableTimes.push({
'msValue': 0,
'display': '12:00 Morning'
});
for (var msValue = 900000; msValue <= 85500000; msValue += 900000) { // 90.000ms = 15 min, 85.500.000ms = 11:45PM
$scope.uiAvailableTimes.push({
'msValue': msValue,
'display': moment(msValue).utc().format("h:mm A")
})
}
var dayMS = 86400000 - 1;
$scope.uiAvailableTimes.push({
'msValue': dayMS,
'display': '12:00 Midnight'
});
$scope.closingTimes = $scope.uiAvailableTimes;
function init() {
$scope.uiHoursOfOperation = [] // FROM SERVER
}
});
这很好用。但我也有来自服务器的数据。这意味着我的选择字段是通过 ng-model 预先选择的。
如何从控制器调用$scope.automaticallySelectClosingTime()。也许在init() 里面。这样它还可以在init() 函数调用或页面加载时创建第二个下拉列表。而且我不必在控制器中创建$scope.uiAvailableTimes。
工作示例:PLUNKER
【问题讨论】:
-
看看这里:stackoverflow.com/a/24161191/264607 了解如何在你的指令上公开一个 api
-
因为
ng-repeat创建了多个子作用域,所以该函数会被多次实例化。没有可靠的方法来做到这一点。 (有一些不值得麻烦的古怪方法)。最好的方法是让ng-change在父控制器中调用一个带有项目索引的函数,即ng-change="updateClosingTimeChoices($index)"。只需在开放时间更改时更新关闭时间选项。 -
目前,我正在做 ng-change。就像当我更改第一个下拉列表时,第二个下拉列表做更新(您可以看到示例第二个下拉列表在第一个下拉列表的选定值之后 15 分钟开始)。但是我还需要在页面加载后加载第一个下拉数据时更改第二个下拉列表。我最初需要以某种方式触发 scope.automaticallySelectClosingTime()
标签: javascript angularjs angular-directive