我正在尝试向表单字段添加maxlength验证,但是当我将其添加到表单字段时,它表示任何长度都是无效的,并且始终将$ scope变量设置为“ undefined”。

在此处检查:http://jsfiddle.net/stevenr4/41L26apv/

Javascript:

var myApp = angular.module('myApp',[]);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.name = 'Superhero';
    $scope.data = {
        'person1': {
            'firstname': "Steve",
            'lastname': "Rogers",
            'maxlength': 5
        },
        'person2': {
            'firstname': "Bob",
            'lastname': "Ross",
            'maxlength': 10
        }
    };

    $scope.pkeys = ['person1', 'person2'];

    $scope.log = function() {
        console.log($scope.data);
    }
}


HTML:

<div ng-controller="MyCtrl">
  Hello, {{name}}!<br>
  Sir, {{data.person1.firstname}} {{data.person1.lastname}}!<br>
  and, {{data.person2.firstname}} {{data.person2.lastname}}!<br>

  <div ng-repeat="key in pkeys track by $index">
    {{key}}<br>
    <input type="text" ng-model="data[key].firstname" ng-maxlength="data[key].maxlength"><br>
    <input type="text" ng-model="data[key].lastname" ng-maxlength="data[key].maxlength"><br>
  </div>

  <button ng-click="log()">
    Log the data
  </button>
</div>


有人可以帮我解决这个问题,或者至少可以向我解释一下吗?

最佳答案

试试这个=> ng-maxlength =“ {{..}}”“

<div ng-controller="MyCtrl">
  Hello, {{name}}!<br>
  Sir, {{data.person1.firstname}} {{data.person1.lastname}}!<br>
  and, {{data.person2.firstname}} {{data.person2.lastname}}!<br>

  <div ng-repeat="key in pkeys track by $index">
    {{key}}<br>
    <input type="text" ng-model="data[key].firstname" ng-maxlength="{{data[key].maxlength}}"><br>
    <input type="text" ng-model="data[key].lastname" ng-maxlength="{{data[key].maxlength}}"><br>
  </div>

  <button ng-click="log()">
    Log the data
  </button>
</div>

关于javascript - 为什么此ng-maxlength将我的有效输入设置为undefined?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46396817/

10-12 16:20