指令更新父范围值 [英] Directive updates parent scope value
本文介绍了指令更新父范围值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用引导,日期选择器其选择范围的能力天。我试图把它放在角指令,并期望更新父范围值时的日期改变,日期格式必须是整周(20-04-2015 - 26-04-2015)
I use bootstrap-datepicker for its ability to select a range of days. I try to put it in Angular directive and expect to update the parent scope value when the date changed, and the date format must be in the whole week (20-04-2015 - 26-04-2015)
var app = angular.module('angular.controls.weekDatePicker', [])
app.directive('weekDatePicker', ['$filter', '$parse', function ($filter, $parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
var ngModelParseFn = $parse(attrs.ngModel);
element.datepicker({
minViewMode: parseInt(attrs.minviewmode),
format: attrs.format,
language: "vi"
}).on('changeDate', function (e) {
scope.$apply(function () {
console.log(scope.$parent);
if (attrs.week == 'true') {
}
else {
// code
}
});
});
element.datepicker('update', new Date()); //reset to now
if (attrs.week == 'true') {
scope.$watch(function () {
return ngModelCtrl.$modelValue;
}, function (newValue) {
var date = element.data().datepicker.viewDate;
var startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
var endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
startDate = $filter('date')(startDate, 'dd-MM-yyyy');
endDate = $filter('date')(endDate, 'dd-MM-yyyy');
console.log(scope.$parent.fixtureDate); //fail to get parent scope value ?
var dateText = startDate + ' - ' + endDate;
ngModelParseFn.assign(scope, dateText);
});
}
scope.$on("$destroy",
function handleDestroyEvent() {
element.datepicker('remove');
}
);
}
};
}]);
查看:
<input week-date-picker ng-model="fixtureDate" minviewmode="0" format="MM-yyyy" class="form-control" week="true" style="width:200px" />
推荐答案
我已经做了一个回调版本(的 Plunker )。
I've done a version with a callback (Plunker).
JS
element.datepicker({
minViewMode: parseInt(attrs.minviewmode),
format: attrs.format,
language: "vi"
}).on('changeDate', function(e) {
var date = e.date;
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1); // 0 = january
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
var startDate = firstDay.getDate() + '-' + (firstDay.getMonth() + 1) + '-' + firstDay.getFullYear();
var endDate = lastDay.getDate() + '-' + (lastDay.getMonth() + 1) + '-' + lastDay.getFullYear();
scope.changeDate({startDate: startDate, endDate: endDate});
});
请注意这指令;
scope: {changeDate: "&"},
index.html的
index.html
$scope.fixtureDate = {
startDate: startDate,
endDate: endDate
};
$scope.updateFixtures = function(startDate, endDate) {
$scope.fixtureDate.startDate = startDate;
$scope.fixtureDate.endDate = endDate;
};
这篇关于指令更新父范围值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文