所以我正在使用AngularJS处理一个小型登录表单,使用ng-repeat指令删除重复的代码似乎非常自然。一切都非常自然,除了ng-show中的任何类型的绑定之外都很好用,这是事情变得不直观和分解的地方。到目前为止,这项工作的小提琴可以找到here。
我想知道为什么ng-show的所有内容都会崩溃?如果我转储ng-repeat并复制代码,一切都适用于所有三个ng-show实例,假设我手动键入对元素和值的引用。
下面是小提琴html和javascript的副本:
<div ng-app='loginApp' ng-controller='loginController'>
<form name='loginForm' novalidate>
<div class='form-group' ng-repeat='field in fields'>
<label>{{field.label}}</label>
<input type='{{field.inputType}}' class='form-control' name='{{field.inputName}}' ng-minlength='{{field.minlength}}' ng-maxlength='{{field.maxlength}}' ng-model='field.value' ng-focus='inputFocused'/>
<!-- The ng-show below doesn't work as expected -->
<div ng-show="canShowUserMsgs(inputFocused, loginForm.{{field.inputName}}.$dirty, loginForm.{{field.inputName}}.$invalid)">
<!-- The ng-show below doesn't work as expected -->
<p ng-show="loginForm.{{field.inputName}}.$error.minlength" class='help-block'>Must be more than {{field.minlength}} characters long.</p>
<!-- The ng-show below doesn't work as expected -->
<p ng-show="loginForm.{{field.inputName}}.$error.maxlength" class='help-block'>Must be less than {{field.maxlength}} characters long.</p>
</div>
</div>
</form>
</div>
var loginApp = angular.module('loginApp', []);
loginApp.controller('loginController', function($scope, $http) {
$scope.fields = [
{
label : "User Name",
inputType : "text",
inputName : "userName",
value : "",
minlength : 5,
maxlength : 15
},
{
label : "Password",
inputType : "password",
inputName : "password",
value : "",
minlength : 5,
maxlength : 15
}
];
$scope.canShowUserMsgs = function(inputFocused, inputDirty, inputInvalid) {
return (inputDirty && inputInvalid && !inputFocused); };
});
loginApp.directive('ngFocus', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs, ctrl) {
var modelName = attrs['ngFocus'];
scope[modelName] = false;
element.bind('focus', function(evt) {
scope.$apply(function() {scope[modelName] = true;});
}).bind('blur', function(evt) {
scope.$apply(function() {scope[modelName] = false;});
});
}
}
}]);
答案 0 :(得分:1)
这不起作用:<p ng-show="loginForm.{{field.inputName}}.$error.minlength"
因为花括号表达式的解释只发生一次,不是两次传递:一次生成没有任何花括号的绑定路径,然后是第二,评估范围的绑定路径。它不是那样的。一切都在一次通过。因此,将其转换为控制器函数调用:
<p ng-show="minLength(field)"
答案 1 :(得分:1)
您必须在ng-form
中添加ng-repeat
,并需要对如何使用ng-show进行一些修改。检查代码的工作示例。