我的 Angular 应用程序中有一个按钮,它将动态地向我的应用程序添加一个输入元素。我想将模型附加到此元素并将其放入监视组以跟踪任何更改。如果用户添加多个输入元素,我想在监视组中添加所有这些模型并跟踪哪个元素改变了它的值。我怎样才能做到这一点?
<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>