2017-09-25 50 views
0

我想將maxlength驗證添加到我的表單字段,但是當我添加它時,它表示任何長度都是無效的,並始終將我的$ scope變量設置爲'undefined'。爲什麼ng-maxlength將我的有效輸入設置爲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> 

有人可以幫我解決這個問題,或者至少給我講解一下?

回答

1

試試這個=> 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> 
+0

這個工作對我來說,只要嘗試過了的小提琴,它是完美的! http://jsfiddle.net/stevenr4/41L26apv/1/ –

相關問題