尝试触发更改时出错

时间:2014-05-08 10:43:45

标签: angularjs validation

我在表单中有2个文本框,它完全相同,因为它是一个指令,通过带有隔离范围的ng-repeat进行渲染。

<form name="inputForm" class="input-icon right"
      ng-class="{'has-error': hasError()}">
    <input type="text"
           ng-model="model"
           class="form-control input-medium" name="textbox" ng-required="isRequiredValidation()">
    <ul class="error-message" ng-show="hasError()">
        <li ng-repeat="error in showErrors">{{error.message}}</li>
    </ul>
</form>
<form name="inputForm" class="input-icon right"
      ng-class="{'has-error': hasError()}">
    <input type="text"
           ng-model="model"
           class="form-control input-medium" name="textbox" ng-required="isRequiredValidation()">
    <ul class="error-message" ng-show="hasError()">
        <li ng-repeat="error in showErrors">{{error.message}}</li>
    </ul>
</form>

要验证ng-required。但我想从外部表单触发此验证,我有一个按钮,当我点击时,我触发更改:

$('form input').each(function (i, element) {
    $(element).trigger('change');
});

但是我收到了一个错误:

Error: [$rootScope:inprog] $apply already in progress
http://errors.angularjs.org/1.2.16/$rootScope/inprog?p0=%24apply
    at http://localhost:29549/Scripts/angular-1.2.16/angular.js:78:12
    at beginPhase (http://localhost:29549/Scripts/angular-1.2.16/angular.js:12720:15)
    at Scope.$apply (http://localhost:29549/Scripts/angular-1.2.16/angular.js:12509:11)
    at HTMLInputElement.listener (http://localhost:29549/Scripts/angular-1.2.16/angular.js:16632:15)
    at HTMLInputElement.jQuery.event.dispatch (http://localhost:29549/Scripts/jquery-1.10.2.js:5109:9)
    at HTMLInputElement.elemData.handle (http://localhost:29549/Scripts/jquery-1.10.2.js:4780:46)
    at Object.jQuery.event.trigger (http://localhost:29549/Scripts/jquery-1.10.2.js:5021:12)
    at HTMLInputElement.<anonymous> (http://localhost:29549/Scripts/jquery-1.10.2.js:5705:17)
    at Function.jQuery.extend.each (http://localhost:29549/Scripts/jquery-1.10.2.js:671:23)
    at jQuery.fn.jQuery.each (http://localhost:29549/Scripts/jquery-1.10.2.js:280:17)  

第一个文本框触发器更改确定,但第二个文本框触发更改错误。 请帮我解决这个问题。 我的主要目的是触发从表单外部验证文本框。

2 个答案:

答案 0 :(得分:1)

对我而言似乎与角色所具有的这个开放性问题有关:

https://github.com/angular/angular.js/issues/6364

要解决此问题,您可以将函数包装在$ timeout中,该函数不会调用脏检查(最后一个参数为false),或使用安全应用:

function safeApply(scope, fn) {
    (scope.$$phase || scope.$root.$$phase) ? fn() : scope.$apply(fn);
}

答案 1 :(得分:0)

看起来jQuery trigger()导致为循环中的每个元素调用$apply()

$apply的多次调用导致错误。 FWIW,混合jquery和angular很少是一个好主意,如果你需要jQuery等效操作,通常可以使用jqLit​​e。

修改

我挖出了一些类似的角度代码。 forEach可能更接近你所追求的目标。如果字段为pristine,则会触发“必填字段”错误消息。这样做无需任何手动apply()电话。

$scope.submit = (form) ->
    if form.$valid
        $modalInstance.close($scope.data)
    else
        angular.forEach form, (field) ->
            field.$setViewValue(field.$viewValue) if field.$pristine