gpt4 book ai didi

angularjs - 如何根据用户输入的 $viewValue 更新来更新 ngModel 的 $modelValue

转载 作者:行者123 更新时间:2023-12-04 03:43:35 25 4
gpt4 key购买 nike

假设我有以下指令:

myApp.directive('myDirective', function() {
return {
restrict: 'A',
require: 'ngModel',
scope: {
ngModel: '='
},
link: function(scope, elem, attrs, ngModelCtrl) {
scope.$watch('ngModel', function() {
ngModelCtrl.$modelValue = 'foo';
});
}
}
});

以及以下html:
<input ng-model="name" my-directive></input>

基本上,每当用户更改输入时, my-directive理想情况下,将内部模型值更改为“foo”,同时保持 View 值不变。

但是当我打印出 $scope.name在相应的 Controller 中,它不记录“foo”,它记录用户输入的任何内容。

似乎 ngModelCtrl.$modelValue不是 Controller 正在访问的内容——我是否错误地处理了这个问题?

(同时在范围内观看 ngModel 感觉真的不对,但我不确定其他任何方式。任何建议将不胜感激!)

最佳答案

如果您正在寻找 View 更改,则永远不要注册 watch 。 ngModelController 的 $viewChangeListeners 专门为此目的而设计,并避免在 ngModel 上创建任何额外的监视。您还可以删除 ngModel 上设置的 2 路绑定(bind)。

我可以这样想。

.directive('myDirective', function($parse) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ngModelCtrl) {
/*Register a viewchange listener*/
ngModelCtrl.$viewChangeListeners.push(function(){
/*Set model value differently based on the viewvalue entered*/
$parse(attrs.ngModel).assign(scope, ngModelCtrl.$viewValue.split(','));
});
}
}
});

Demo

反过来考虑它(Credits @Cody)在使用 $parser 时变得更加简洁和恰当。 .
 ngModelCtrl.$parsers.push(function(val) { return val.split(',') });

关于angularjs - 如何根据用户输入的 $viewValue 更新来更新 ngModel 的 $modelValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26172191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com