2

将来のある時点で、必要なディレクティブを要素に追加しようとしています。例では、モデル フィールドが汚れている場合は、要素を必須にします。必要な属性を設定しようとしましたが(少し楽観的です)、要素をコンパイルしてリンクし、古い要素を新しい要素に置き換えようとしています。

私の要素がページから消えるだけですか? 私はこれを正しい方法で行っていますか?

 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();
                                });
                            }
                        };
                    });
4

2 に答える 2

0

Transclusionディレクティブで使用する必要があります。これにより、コンテンツをヤンクし、追加requiredしてからコンパイルすることができます。これは、基本的な概念を説明する優れたチュートリアルです: Egghead.io - AngularJS - Transclusion Basics

于 2013-09-06T14:50:02.020 に答える
-2

実際にそれを行う必要はありません。Angularには実際にディレクティブがありますng-required

見る

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

ng-model を持つ任意のフィールドで ng-required に式を指定すると、true と評価される式に基づいて必要なバリデーターが追加されます。

ドキュメントから

ngRequired(optional){string=}– ngRequired 式が true と評価されたときに、必須属性と必須検証制約を要素に追加します。required 属性にデータ バインドする場合は、required の代わりに ngRequired を使用します。

于 2013-04-09T20:03:38.757 に答える