动态 ngModel 和 ngBind 与自定义指令

Dynamic ngModel and ngBind with a custom directive

本文关键字:自定义 指令 ngBind ngModel 动态      更新时间:2023-09-26

我想创建一个指令,为每个输入字段创建一个自动生成的ngModel,在每个输入字段下面都有一个ng绑定到上面元素的ngModel,所以这是我到目前为止所做的指令

  app.directive('cmsInput', function() {
    return {
        restrict: 'E',
        compile: function(element, attrs)
        {
            var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="form-group"  ng-controller="DashboardController">' +
                '<label class="col-sm-2 control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="col-sm-10">' +
                    '<input ng-model="content.'+attrs.formId +'" type="' + type + '" class="form-control" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '<span ng-bind="content.'+attrs.formId+'"></span></div>' +
                '</div>';
            element.replaceWith(htmlText);
        }
    }
})

所以这个 direcive 给了我输入元素,但 ngBind 不起作用.

这是 HTML

<!doctype html>
<html lang="en">
<head>
<title>Test Title</title>
</head>

<body>
<cms-input label="Email address" form-id="emailAddress" type="email" required /></cms-input>
<cms-input label="Name" form-id="name" type="text"/></cms-input>
<cms-input label="Header" form-id="header" type="text"/></cms-input>
<cms-input label="Password" form-id="password" type="password"/></cms-input>

</body>
</html>

我在这里看到了几件事,但真正导致问题的唯一一件事是没有将 $scope.content 初始化为对象。您可以在此处查看一个工作示例:http://jsbin.com/bocuzi/1/edit?html,js,output

另一件可能让您失望的事情是,如果您使用电子邮件字段而不是输入有效的电子邮件地址来测试这一切。由于 ngModelController 的工作方式,除非通过验证,否则它实际上不会设置$scope值。其他字段都没有此限制,因为它们使用的是文本或密码类型。

希望有帮助。