如果引用属性是由指令创建的,则ng-show不起作用

时间:2015-05-26 08:44:41

标签: angularjs angularjs-directive ng-show generated

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

请参阅此处的示例。 (静态密码代码有效,生成的用户代码不可用)

&#13;
&#13;
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);
            }
        }
    });
&#13;
<!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>
&#13;
&#13;
&#13;

问题似乎是myForm.user是在指令

中创建的

1 个答案:

答案 0 :(得分: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">