我檢查了所有有類似主題的未解決問題,但都沒有給出適當的工作解決方案,這讓我發瘋,這就是爲什麼我打開這個問題。用於datepicker的AngularJS自定義指令不會更新ng-model
我的自定義指令看起來像
angular.module('angularSampleApp') .directive('datepicker', function() {
'use strict';
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, el, attr, ngModel) {
$(el).datepicker({
maxDate: 0 ,
onSelect: function(dateText) {
scope.$apply(function(){
ngModel.$setViewValue(dateText);
ngModel.$viewValue = dateText;
ngModel.$render();
});
}
});
}
};
});
我用指令這樣
<input type="text" id="datepicker" datepicker ng-model="jumpDate">
<a name="jump" id="jump" title="Jump" ng-click="jumpToDate()">Jump</a>
,並在控制器我有這樣的事情:
$scope.jumpToDate = function() {
console.log($scope.jumpDate);
};
但是指令不更新$ scope.jumpDate並且它總是未定義的,即使我在控制器中設置了默認值n不斷更新,dateText具有適當的價值。
我正在使用角度構建1.4.1
你只需要'ngModel。$ setViewValue(dateText)'和你不需要把它包裝成'$範圍。$ apply'。 – zeroflagL
@zeroflagL仍然沒有試過那一個... – vaske
可能相同於http://stackoverflow.com/a/29194068/2435473 –