[英]How to pass data from directive to controller?
我目前正在將插件集成到我的angular應用程序中,並且正在嘗試將其轉換為指令。 我擺弄了插件的事件和方法,但未能獲得所需的結果。 這是我的代碼:
的HTML
<div class="input-daterange datepicker full" rangepicker ng-model="packer.selected.date">
<i class="fa fa-calendar"></i>
<div class="inputs datepicker">
<input
ng-model="packer.selected.date.start"
name="start"
value="<% packer.initData.dateStart %>">
<span class="add-on">-</span>
<input
ng-model="packer.selected.date.end"
name="end"
value="<% packer.initData.dateStart %>">
</div>
</div>
Javascript:
Application.directive('rangepicker', function() {
return {
restrict: 'A',
link: function(scope, element, attrs, ngModel) {
$(element).datepicker({
format: 'yyyy-mm-dd'
});
$(element).on('changeDate', function(){
/*
$(element).find('input').each(function(){
$(this).trigger('input');
}) */
})
}
};
});
Application.controller('PackingStatisticsController', ['$scope', '$http', 'initData', function($scope, $http, initData) {
var packer = this;
packer.initData = initData;
packer.selected = {
date : {
start : "",
end : ""
},
user : ""
}
packer.log = function()
{
console.log(packer.selected);
}
}]);
我讀過任何我認為與我的問題有關的東西,但是我沒有擺脫混亂的面紗。 注釋后的代碼應該觸發輸入值更改事件,我希望它將更新模型。 我無法理解在html中指定的模型與指令的數據相符的位置。
https://bootstrap-datepicker.readthedocs.org/en/latest/index.html這是我正在使用的插件。
您可以像這樣從控制器的作用域傳遞要修改的模型作為屬性(查看scope屬性):
Application.directive('rangepicker', function() {
return {
restrict: 'A',
scope : {
model : '='
}
link: function(scope, element, attrs, ngModel) {
$(element).datepicker({
format: 'yyyy-mm-dd'
});
$(element).on('changeDate', function(){
/*
$(element).find('input').each(function(){
$(this).trigger('input');
}) */
})
}
};
});
並在html中:
<div class="input-daterange datepicker full" model="myModelVar" rangepicker ng-model="packer.selected.date">
現在,myModeVar是兩種可綁定數據的方式。 在指令中對其進行更改后,其范圍也會隨之更改。
在控制器中:
Application.controller('PackingStatisticsController', ['$scope', '$http', 'initData', function($scope, $http, initData) {
$scope.myModelVar = ...;
}]);
las,我做到了!
Application.directive('rangepicker', function() {
return {
restrict: 'A',
require: 'ngModel', // added the ngmodel requirement
scope : {
ngModel: "="
}, // also added this, which if i understood well
// makes the 2 way data binding possible
link: function(scope, element, attrs) {
$(element).datepicker({
format: 'yyyy-mm-dd'
});
$(element).on('changeDate', function(){
var values = $(element).find('input');
var interval = {
start : values[0].value,
end : values[1].value
}
scope.$apply(function(){
// and here i update the given model scope (packer.selected.data)
scope.ngModel = interval;
});
})
}
};
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.