我有一个控制器AppCtrl
为
scope.transaction = {}
索引看起来像
<div class="control-group">
<label class="control-label">Date</label>
<div class="controls">
<div class="control-group input-append date form_datetime">
<date-time-picker data-ng-model="transaction.date"></date-time-picker>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label">Amount</label>
<div class="controls">
<div class="input-append">
<input type="text" name="transactionAmount" ng-model="transaction.amount" required>
</div>
我的自定义指令看起来像
angular.module('customDirectives', []).directive('dateTimePicker', function() {
return {
restrict: 'E',
replace: true,
scope: {
transaction['date']: '=' # COMPILATION ERROR HERE
},
template: '<div class="control-group input-append date form_datetime">'+
'<input type="text" readonly data-date-format="yyyy-mm-dd hh:ii" name="transactionDate" ng-model="transaction.date" data-date-time required>'+
'<span class="add-on"><em class="icon-remove"></em></span>'+
'<span class="add-on"><em class="icon-th"></em></span>'+
'</div>',
link: function(scope, element, attrs, ngModel) {
var input = element.find('input');
element.datetimepicker({
format: "yyyy-mm-ddThh:ii:ssZ",
showMeridian: true,
autoclose: true,
todayBtn: true,
pickerPosition: 'bottom-left'
});
element.bind('blur keyup change', function(){
console.log('binding element');
scope.$apply(date);
});
function date() {
console.log('setting date',input.val());
scope.ngModel = input.val();
}
date(); // initialize
}
}
});
我想将我的指令中的日期值分配给$scope.transaction.date
,但它因编译错误而失败,我该如何实现?
答案 0 :(得分:6)
scope: {
transaction['date']: '=' # COMPILATION ERROR HERE
},
应该是
scope: {
transactionDate: '='
},
和
<date-time-picker data-ng-model="transaction.date"></date-time-picker>
应该是
<date-time-picker transaction-date="transaction.date"></date-time-picker>
然后在你的指令中你可以调用scope.transactionDate = myValue;
在范围内。$ apply();
编辑:如果你想在你的指令中使用ng-model,你可以使用
....
restrict: 'E',
require: '?ngModel',
....
并且
controller.$setViewValue(value); //this will in directive code where you want set the value of the ng-model bound variable.
在Html中
<date-time-picker data-ng-model="transaction.date"></date-time-picker>