AngularJS数学表达式为ng-model

时间:2017-05-29 15:38:49

标签: javascript angularjs

我是AngularJS开发的新手。我正在开发一个项目,其中我有一组输入表。我使用ng-model来计算基于其他两个输入的输入。 例如,我有一个学生对象,其中包含正确,错误和未尝试的问题。对于许多学生,我使用的是ng-repeat,如下所示。但是,当我执行ng-model=some-expression时,它会在控制台中输出一个错误,指出表达式是不可分配的。但它的确有效。我很困惑,有没有办法解决这个问题。 感谢

HTML:

<tr ng-repeat="student in studentData">
    <td>{{ student.name }}</td>
    <div  ng-show="selectedSubj.indexOf('Physics') > -1">
        <td><input type="number" min="0"  ng-model="student.correctPhysics" required>
        <input type="number" min="0"  ng-model="student.incorrectPhysics" required>
        <input type="number" min="0"  ng-model="student.unattemptedPhysics=noOfQues-student.correctPhysics-student.incorrectPhysics"></td>
    </div>
</tr>

控制器代码:

$scope.studentData = ['Akhilesh'];
for(var i = 0; i < $scope.selectedStudents.length; i++){
  $scope.studentData.push({name: $scope.selectedStudents[i].name, batch: $scope.selectedStudents[i].batch, 
    correctPhysics: 0, incorrectPhysics: 0, unattemptedPhysics: 0,
    correctChemistry: 0, incorrectChemistry: 0, unattemptedChemistry: 0,
    correctMaths: 0, incorrectMaths: 0, unattemptedMaths: 0,
    correctBio: 0, incorrectBio: 0, unattemptedBio: 0, total: ''});
}

1 个答案:

答案 0 :(得分:0)

angular不允许您在ng-model内编写表达式。因此,您可以在ng-init

中执行此操作
<input type="number" min="0" ng-init="student.unattemptedPhysics=noOfQues-student.correctPhysics-student.incorrectPhysics"  ng-model="student.unattemptedPhysics"></td>

angular.module("app",[])
.controller("ctrl",function($scope){

$scope.studentData = [{"name":"Akhilesh","batch":"A1","correctPhysics":12,"incorectPhysics":3,"unatemptedPhysics":0,"crrectChemistry":0,"ncorrectChemistry":0,"unattemptedChemisry":0,"correctMaths":0,"incorrectMaths" : 0,"unattemptedMaths":0,"correctBio":0,"ncorrectBio":0,"unatemptedBio":0,"tota":45}]
 
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<table>
 <tr ng-repeat="student in studentData">
    <td>{{ student.name }}</td>
    <div  ng-show="selectedSubj.indexOf('Physics') > -1">
        <td><input type="number" min="0"  ng-model="student.correctPhysics" required ng-change="student.unattemptedPhysics=noOfQues-student.correctPhysics-student.incorrectPhysics">
        <input type="number" min="0"  ng-model="student.incorrectPhysics" required>
        <input ng-init="student.unattemptedPhysics=noOfQues-student.correctPhysics-student.incorrectPhysics" type="number"   ng-model="student.unattemptedPhysics"></td>
    </div>
</tr>
</table>
</div>