gpt4 book ai didi

javascript - 带有自定义指令的动态 ngModel 和 ngBind

转载 作者:行者123 更新时间:2023-12-03 11:00:35 25 4
gpt4 key购买 nike

我想创建一个指令,为每个输入字段创建一个自动生成的 ngModel,并在每个输入字段下方创建一个 ng-bind 到上面元素的 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);
}
}
})

所以这个指令给了我输入元素,但 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 值。其他字段都没有该限制,因为它们使用的是文本或密码类型。

希望有帮助。

关于javascript - 带有自定义指令的动态 ngModel 和 ngBind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28111841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com