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

删除范围: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 回答