簡體   English   中英

Angular.js:將日歷值從指令傳遞到控制器

[英]Angularjs: Pass calendar value from directive to controller

我有這個設備預訂系統,它有預訂表格,其中包括帶有彈出日歷的字段。 因為我在ng-repeat中有此日歷彈出窗口,所以我為此創建了一個指令,以便可以使用。

但是,我的問題是,保存預留時,我無法將日歷值從指令傳遞給控制器​​。

我該怎么辦?

這是保存功能:

 $scope.Start = ""; $scope.saveReservation = function (newReservation, equipment) { $scope.$emit('WORKING', true); newReservation.EquipmentID = equipment.ID; newReservation.StartDate = $scope.Start; reservationService.addNew(newReservation) .then(function (response) { $scope.showReservationForm = false; reservationService.getAll() .then(function (response) { $scope.reservations = response.d.results; $scope.$emit('WORKING', false); alert("Your reservation was succesful.") }, function (reason) { $scope.$emit('WORKING', false); alert('You reservation failed because of error ' + reason); }); }); }; 

這是指令:

 "use strict"; (function () { angular.module("App").directive('myRepeatDirective', [ function () { return { link: function (scope, element, attrs) { if (scope.$last) { $('.bootstrap-datepicker1').datepicker({ format: "dd/mm/yyyy", autoclose: true }); $('#bootstrap-datepicker1').on('change', function () { scope.Start = $('#bootstrap-datepicker1').val() }); $('.bootstrap-datepicker2').datepicker({ format: "dd/mm/yyyy", autoclose: true }); $('#bootstrap-datepicker2').on('change', function () { scope.End = $('#bootstrap-datepicker2').val() }); } } }; }]) })(); 

這是輸入:

 <input style="width: 200px;" type="text" class="bootstrap-datepicker1" id="bootstrap-datepicker1" data-ng-model="Start" placeholder=" dd.mm.yyyy" /> 

在指令定義對象上使用“ scope”屬性。

https://docs.angularjs.org/guide/directive

您也可能會發現此有用

https://github.com/angular/angular.js/wiki/Understanding-Scopes

從指令中注入$rootScope並在要傳遞數據時進行廣播:

$rootScope.$broadcast("calendarValue", {value: new Date(), foo: "bar"});

現在,在您的控制器中,獲取要接收的值:

$scope.$on("calendarValue", function(e, data) {
    console.log(data.foo === "bar");
    $scope.selectedValue = data.value;
});

使用scope。$ apply使角度知道值在角度范圍之外發生了變化。 其他角度不知道該值已更改。

$('#bootstrap-datepicker1').on('change', function () {
   scope.$apply(function(){
       scope.Start = $('#bootstrap-datepicker1').val()
   }) 
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM