我有一个带有文本输入和验证消息的表单,如果输入发生更改,则必须显示该表单。(这个例子没有意义,但它被简化为基本问题)我想在我的 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 是在指令中创建的