【问题标题】:Angularjs: validation not working when control is based on directiveAngularjs:当控制基于指令时验证不起作用
【发布时间】:2013-06-11 19:32:30
【问题描述】:

作为 Angularjs 的新手,我正在使用指令在 Angularjs 中创建文本框标签组合。它运行良好,但 我无法进行验证。这是一个精简的示例。

HTML:

<form name="form" novalidate ng-app="myapp">
<input type="text" name="myfield" ng-model="myfield" required />{{myfield}}
<span ng-show="form.myfield.$error.required">ERROR MSG WORKING</span> 
<br>
<div mydirective FIELD="myfield2" />
</form>

Javascript:

var myapp = angular.module('myapp', []);

myapp.directive('mydirective', function () {
    return {
        restrict: 'A',
        scope: { ngModel: '=' },
        template: '<input type="text" name="FIELD" ng-model="FIELD" />{{FIELD}}
        <span ng-show="form.FIELD.$error.required">ERROR MSG NOT WORKING</span>'
    };
});

硬编码输入 - myfield - 有效,另一个 - myfield2 - 无效(绑定有效,只是不是必需的错误消息)。

我如何告诉 ng-show 属性在 form.FIELD.$error.required 中由 myfield2“替换”FIELD >?

这是jsFiddle

【问题讨论】:

  • 在jsFiddle中,指令中定义的输入不包含“required”属性。这不是导致问题的原因,但需要获得您想要的行为。
  • @GeorgeThomas:谢谢,我会解决这个问题的。

标签: angularjs angularjs-directive


【解决方案1】:

问题是你的指令为指令创建了一个新的作用域,这个新作用域无法访问父作用域中的表单对象。

我想出了两个解决方案,但我怀疑有一种更优雅的“Angular”方法可以做到这一点:

传递表单对象

你的观点变成:

<div mydirective FIELD="myfield2" form="form" />

以及范围定义对象:

return {
    restrict: 'A',
    scope: {
        ngModel: '=',
        form: '='
    },
    template: '<input type="text" name="FIELD" ng-model="FIELD" required/>{{FIELD}}<span ng-show="form.FIELD.$error.required">ERROR MSG NOT WORKING</span>'
};

我已经用这个代码更新了小提琴:http://jsfiddle.net/pTapw/4/

使用控制器

return {
    restrict: 'A',
    controller: function($scope){
        $scope.form = $scope.$parent.form;   
    },
    scope: {
        ngModel: '='
    },
    template: '<input type="text" name="FIELD" ng-model="FIELD" required/>{{FIELD}}<span ng-show="form.FIELD.$error.required">ERROR MSG NOT WORKING</span>'
};

【讨论】:

  • 太棒了!我第一次看到这个工作,这是完全有道理的。已经是一种学习体验——我从未想过会创建一个新的范围。
  • 我刚刚添加了第二种方法。虽然看起来都没有那么优雅。
  • 非常感谢!您的第一个版本已经实现并在项目中运行。明天我会玩第二个。优雅是另一个问题 - 你无法想象看到这件事情变得生动起来我是多么高兴:-)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
  • 2018-09-07
相关资源
最近更新 更多