无法在 ng-show 中绑定 ng-show 中的 ng-repeat



因此,我正在使用AngularJS编写一个小型登录表单,通过使用ng-repeat指令删除重复代码似乎非常自然。除了ng-show内部的任何绑定之外,一切都非常自然,运行良好,这就是事情变得不直观和崩溃的地方。到目前为止的一些工作可以在这里找到。

我想知道的是为什么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;});
      });
    }
  }
}]);

您必须在ng-repeat中添加ng-form,并且需要对如何使用ng-show进行一些修改。检查代码的工作示例。

工作副本

这不起作用:<p ng-show="loginForm.{{field.inputName}}.$error.minlength"因为大括号表达式的解释只发生一次,没有两次传递:一次生成没有任何大括号的绑定路径,然后第二次根据作用域计算绑定路径。不是那样的。一切都发生在一个单一的过程中。因此,将其转换为控制器函数调用:

<p ng-show="minLength(field)"

最新更新