2017-09-15 53 views
0

我想通過在輸入[數字]中鍵入數字來填充輸入。按數字填充輸入angularjs

爲什麼這不起作用

// Code goes here 
 

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

 
app.controller('MainCtrl', function($scope) { 
 
    $scope.lengInput = { 
 
     count: 0, 
 
     values: [], 
 
     fill: function(limit) { 
 
      var sequence = []; 
 
      for (var i = 0; i < limit; i++) { 
 
       sequence.push(i); 
 
      } 
 
      return sequence; 
 
     } 
 
    }; 
 
});
<!DOCTYPE html> 
 
<html ng-app="app"> 
 

 
    <head> 
 
    <meta charset="utf-8" /> 
 
    <title>AngularJS Plunker</title> 
 
    
 
    <link rel="stylesheet" href="style.css" /> 
 
    <script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.js" data-semver="1.5.11"></script> 
 
    <script src="script.js"></script> 
 
    </head> 
 

 
    <body ng-controller="MainCtrl"> 
 
    <p>Hello {{name}}!</p> 
 
    <input ng-model="lengInput.count" type="number" min="1" max="20"> 
 
    <ul> 
 
     <li ng-repeat="i in lengInput.fillSequence(lengInput.count)"> 
 
      <input ng-model="lengInput.values[i]" /> 
 
     </li> 
 
    </ul> 
 
    </body> 
 

 
</html>

因爲這

工作

JSFiddle Demo

請找我的錯誤。

回答

1

取而代之的是功能,直接連接到ng-repeat的,你可以使用ng-init並初始化的$scope.lengInput.values並添加ng-change$scope.lengInput.count是越來越設置輸入字段,因此該功能沒有得到每次運行,而不是運行只有當輸入框中的值已經改變時!

// Code goes here 
 

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

 
app.controller('MainCtrl', function($scope) { 
 
    $scope.lengInput = { 
 
    count: 0, 
 
    values: [], 
 
    fill: function(limit) { 
 
     var sequence = []; 
 
     for (var i = 0; i < limit; i++) { 
 
     sequence.push(i); 
 
     } 
 
     $scope.lengInput.values = sequence; 
 
    } 
 
    }; 
 
});
<!DOCTYPE html> 
 
<html ng-app="app"> 
 

 
<head> 
 
    <meta charset="utf-8" /> 
 
    <title>AngularJS Plunker</title> 
 

 
    <link rel="stylesheet" href="style.css" /> 
 
    <script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.js" data-semver="1.5.11"></script> 
 
    <script src="script.js"></script> 
 
</head> 
 

 
<body ng-controller="MainCtrl" ng-init="lengInput.fill(lengInput.count)"> 
 
    <p>Hello {{name}}!</p> 
 
    <input ng-model="lengInput.count" type="number" min="1" max="20" ng-change=" lengInput.fill(lengInput.count)"> 
 
    <ul> 
 
    <li ng-repeat="i in lengInput.values"> 
 
     <input ng-model="lengInput.values[i]" /> 
 
    </li> 
 
    </ul> 
 
</body> 
 

 
</html>