AngularJS - 如何更改自定义指令中 ngModel 的值? [英] AngularJS - how to change the value of ngModel in custom directive?
本文介绍了AngularJS - 如何更改自定义指令中 ngModel 的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们看看我的指令:
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 的值?
So, how do I change the value of the ng-model?
推荐答案
有不同的方法:
$setViewValue()
更新视图和模型.大多数情况下就足够了.- 如果您想断开视图与模型的连接(例如,模型是一个数字,而视图是一个带有千位分隔符的字符串),那么您可以直接访问
$viewValue
和$modelValue代码>
- 如果您还想覆盖
ng-model
的内容(例如,指令更改小数位数,同时更新模型),请注入ngModel: '='
在作用域上设置scope.ngModel
$setViewValue()
updates the view and the model. Most cases it is enough.- If you want to disconnect view from the model (e.g. model is a number but view is a string with thousands separators) then you could access directly to
$viewValue
and$modelValue
- If you also want to overwrite the content of
ng-model
(e.g. the directive changes the number of decimals, updating also the model), injectngModel: '='
on the scope and setscope.ngModel
例如
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
}
...
链接:
- 在此处 讨论了第一个选项
- NgModelController 官方文档
这篇关于AngularJS - 如何更改自定义指令中 ngModel 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文