首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >向现有元素添加指令

向现有元素添加指令
EN

Stack Overflow用户
提问于 2013-04-10 03:34:09
回答 2查看 1.3K关注 0票数 2

我正在尝试在将来的某个时候将所需的指令添加到元素中。在本例中,如果model字段是脏的,则将元素设为必需的。我尝试只设置必需的属性(有点乐观),现在我正在编译和链接元素,并尝试用新元素替换旧的elemenet。

我的元素就这么从页面上消失了?我这样做对吗?

代码语言:javascript
运行
复制
 app.directive('requiredIfDirty', function ($compile, $timeout) {
                        return {
                            restrict: "A",
                            require: // element must have ng-model attribute.
                            'ngModel',
                            link: // scope = the parent scope
                            // elem = the element the directive is on
                            // attr = a dictionary of attributes on the element
                            // ctrl = the controller for ngModel.
                            function (scope, elem, attr, ctrl) {
                                var unsubscribe = scope.$watch(attr.ngModel, function (oldValue, newValue) {
                                    if(angular.isUndefined(oldValue)) {
                                        return;
                                    }
                                    attr.$set("required", true);
                                    $timeout(function () {
                                        var newElement = $compile(elem)(scope);
                                        elem.replaceWith(newElement);
                                    }, 1);
                                    unsubscribe();
                                });
                            }
                        };
                    });
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-09-06 22:50:02

你必须在你的指令中使用Transclusion。这将允许您拉出内容,将required附加到它,然后编译它。这是一个很好的教程,它解释了基本概念:Egghead.io - AngularJS - Transclusion Basics

票数 0
EN

Stack Overflow用户

发布于 2013-04-10 04:03:39

你实际上并不需要这样做。Angular实际上有一个指令ng-required

看见

http://docs.angularjs.org/api/ng.directive:input.text

您可以在任何具有ng-model的字段上向ng-required提供一个表达式,它会根据计算结果为true的表达式向其添加所需的验证器。

从文档中

true ngRequired(optional) -

-当ngRequired表达式的计算结果为true时,向元素添加必需的属性和必需的验证约束。如果要将数据绑定到所需的属性,请使用ngRequired而不是required。

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15910920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档