让我们来看看我的指示:
angular.module('main').directive('datepicker', [
function() {
return {
require: '?ngModel',
link: function(scope, element, attributes, ngModel) {
ngModel.$modelValue = 'abc'; // this does not work
// how do I change the value of the model?
那么,我该如何更改ng-model的值?
答案 0 :(得分:48)
有不同的方法:
$setViewValue()
更新视图和模型。大多数情况就足够了。$viewValue
和$modelValue
ng-model
的内容(例如,指令更改小数位数,同时更新模型),请在范围上注入ngModel: '='
并设置scope.ngModel
< / LI>
醇>
e.g。
return {
restrict: 'A',
require: 'ngModel',
scope: {
ngModel: '='
},
link: function (scope, element, attrs, ngModelCtrl) {
function updateView(value) {
ngModelCtrl.$viewValue = value;
ngModelCtrl.$render();
}
function updateModel(value) {
ngModelCtrl.$modelValue = value;
scope.ngModel = value; // overwrites ngModel value
}
...
<强>链接:强>
答案 1 :(得分:28)
要使用复杂的绑定表达式,您应该使用$parse服务和assign
方法。
有关更多信息,请观看此视频来自ng-conf - 所有关于使用ng-model指令可以做的很酷的事情:https://www.youtube.com/watch?v=jVzymluqmg4
app.directive('datepicker', ['$parse',
function($parse) {
return {
require: '?ngModel',
link: function(scope, element, attributes, controller) {
// $parse works out how to get the value.
// This returns a function that returns the result of your ng-model expression.
var modelGetter = $parse(attributes['ngModel']);
console.log(modelGetter(scope));
// This returns a function that lets us set the value of the ng-model binding expression:
var modelSetter = modelGetter.assign;
// This is how you can use it to set the value 'bar' on the given scope.
modelSetter(scope, 'bar');
console.log(modelGetter(scope));
}
};
}
]);
答案 2 :(得分:4)
您尝试过的是实际工作:see this Plunker
你不会看到&#34;它在输入中,因为以这种方式更改模型并不会调用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';
}
}
};
}]);
答案 3 :(得分:1)
适用于我网站上的DatePicker
link: function(scope, elem, attrs, ngModel) {
scope.$apply(function(){
ngModel.$viewValue = value;
}
}
答案 4 :(得分:1)
这是我遇到过的最佳解释。这对我来说很有帮助,并且在这里汇集了许多其他答案的细节。
提示:小心阅读整篇文章而不是浏览它,否则你可能会错过一些关键部分!
https://www.nadeau.tv/post/using-ngmodelcontroller-with-custom-directives/