0

テキスト入力と、入力が変更された場合に表示する必要がある検証メッセージを含むフォームがあります。(この例は意味がありませんが、基本的な問題に縮小されます) angularJS ディレクティブで生成したいものは次のとおりです。

<p>Username:<br> 
  <input type="text" name="user" ng-model="user" required> 
  <span style="color:red" ng-show="myForm.user.$dirty"> Username is dirty.</span>
</p>

こちらの例をご覧ください。(静的パスワード コードは機能しますが、生成されたユーザー コードは機能しません)

var app = angular.module('myApp', []);
app.controller('myCrtl', function($scope) {
    $scope.user = 'MyName';
    $scope.passwd = 'MyPw';
})
.directive("mytest", function($compile){
        return{
      scope: true,
            link: function(scope, element){
                var template = '<input type="text" name="user" ng-model="user" required>'+
'<span style="color:red" ng-show="myForm.user.$dirty">'+
'Username is dirty.</span>';
                var tmpFn= $compile(template);
                var content = tmpFn(scope);
                element.append(content);
            }
        }
    });
<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script>  
<body>

<h2>Validation</h2>

<form ng-app="myApp" ng-controller="myCrtl" 
name="myForm" novalidate>

<!-- the generated code does not work -->
<p mytest>User:<br>
</p>

<!-- the static code works-->
<p>Password:<br>
<input type="text" name="passwd" ng-model="passwd" required>
<span style="color:red" ng-show="myForm.passwd.$dirty">
Password is dirty.</span>
</p>  
</form>


</body>
</html>

問題は、 myForm.user がディレクティブで作成されているようです

4

1 に答える 1

0

Remove scope: true を指定すると、ディレクティブは新しいスコープを作成せず、優先度を設定しません。それでもうまくいかない場合は、このディレクティブを試してください

function dynamicName($compile) {
    return {
        restrict: 'A',
        terminal: true,
        priority: 1000,
        link: function (scope, element, attrs) {
            var name = scope.$eval(attrs.dynamicName);
            if (name) {
                element.attr('name', name);
                element.removeAttr('dynamic-name');
                $compile(element)(scope);
            }
        }
    };
}

このように使う

<input dynamic-name="inputName">
于 2015-05-26T10:25:48.243 に答える