アプリに入力要素を動的に追加するボタンがアプリにありました。モデルをこの要素にアタッチし、変更を追跡するためにウォッチ グループに配置します。ユーザーが複数の入力要素を追加する場合、それらすべてのモデルをウォッチ グループに追加し、どの要素がその値を変更したかを追跡します。これどうやってするの?
<body ng-app="myApp">
<div ng-controller="GpaController" >
<form id="mform">
<select name="grade" ng-model="grade" ng-options="key as key for (key,value) in gradePoints" ></select>
<input type="number" min="1" max="4" ng-model="score">
</form>
<button type="button" ng-click="addElement()">Add</button>
</div>
<script type="text/javascript" src="./app/angular.min.js"></script>
<script type="text/javascript" src="./app/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
angular.module('myApp', [])
.controller('GpaController', ['$scope', '$compile', function($scope, $compile){
$scope.grade = 'A';
$scope.score = 4;
var gradePoints = { 'A': 4, 'A-': 3.7,
'B+': 3.3, 'B': 3.0, 'B-': 2.7,
'C+': 2.3, 'C': 2.0, 'C-': 1.7,
'D': 1, 'F': 0 };
$scope.gradePoints = gradePoints;
$scope.$watchGroup(['grade', 'score'], function(){
console.log($scope.grade)
var n = $scope.gradePoints[$scope.grade] * $scope.score;
console.log(n);
});
$scope.addElement = function(){
var val = '<div><select name="grade" ng-model="grade" ng- options="key as key for (key, value) in gradePoints" > </select><input type="number" min="1" max="4" ng-model="score"><div>';
var ele = $compile(val)($scope);
$("#mform").append(ele);
}
}]);
</script>
</body>