您尝试的实际上是有效的:请参阅此 Plunker
您不会在输入中“看到”它,因为以这种方式更改模型不会调用controller.$render()
设置新的 controller.$viewValue
.
但是你为什么不简单地改变这个$scope
值(除非你不知道,但这会很奇怪):
angular.module('main').directive('datepicker', [function() {
return {
require: '?ngModel',
link: function(scope, element, attributes, controller) {
var model = attributes['ngModel'];
scope[model] = 'bar';
}
};
}]);
在你的 html 中:
<input ng-model="yourVariable" datepicker>
编辑:(动态解决方案)
angular.module('main').directive('datepicker', [function() {
return {
require: '?ngModel',
link: function(scope, element, attributes, controller) {
// get the value of the `ng-model` attribute
var model = attributes['ngModel'];
// update the scope if model is defined
if (model) {
scope[model] = 'bar';
}
}
};
}]);