gpt4 book ai didi

javascript - 为什么 ng-change 没有在 Angular JS 中触发?

转载 作者:行者123 更新时间:2023-12-03 00:47:58 25 4
gpt4 key购买 nike

你能告诉我为什么 ng-change 没有在 Angular js 中触发吗?当我在日期输入字段中输入“abc”时,它仅触发一次。请告诉我如何多次开火这是我的代码

$scope.changedate =function(){
console.log('asda')
}

<li ng-repeat="(key, x) in c">
<p class="input-group" ng-if="x.date=='date'">
<input type="text" ng-change='changedate()' class="form-control" uib-datepicker-popup="{{format}}" ng-model="x.name" is-open="x.opened" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="formats" />
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="open1(x)"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</p>
<input id='{{key}}' ng-if="x.date!='date'" type="text" ng-model='x.name' value="{{x.name=='abc'?'ddd':'hhh'}}"/>
</li>

http://plnkr.co/edit/neixp9ZARRAQ33gKSV9u?p=preview重现此错误的步骤

  1. 运行应用程序。第一个日期字段为空。我刚刚在其中输入了1,然后 ng 更改了触发,之后我输入了 anthing 它不会触发

最佳答案

因为当您输入a时,模型值变为undefined,当您输入b时,模型值未定义,因此没有任何变化,当您输入 c 时,模型再次变为 未定义。这就是为什么不调用 ng-change 的原因。

来自 angularjs 文档:

The ngChange expression is only evaluated when a change in the input value causes a new value to be committed to the model.

It will not be evaluated:

if the value returned from the $parsers transformation pipeline has not changed if the input has continued to be invalid since the model will stay null if the model is changed programmatically and not by a change to the input value

这是我用于此类场景的辅助指令:

angular.module('viewValueChanged', [])
.directive('viewValueChanged', viewValueChangedDirective);


function viewValueChangedDirective() {
return {
restrict: "A",
require: 'ngModel',
link: linkFn
};

function linkFn(scope, elem, attrs, ngModel) {
scope.$watch(function () {
return ngModel.$viewValue;
}, function (newValue, oldValue) {
if (newValue && newValue !== oldValue) {
scope.$parent.$eval(attrs['viewValueChanged']);
}
// in case of user entered invalid value
if(newValue === null) {
scope.$parent.$eval(attrs['viewValueChanged']);
}
});
}
}

并像这样使用它:

 <input uib-datepicker-popup view-value-changed="vm.onFieldsChange() />

关于javascript - 为什么 ng-change 没有在 Angular JS 中触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53166458/

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