javascript - 单击列表中的每个单选按钮后 ng-change 不触发

标签 javascript angularjs angularjs-scope

我正在为我的大学项目创建一个小应用程序,我有一个场景,当用户点击一个单选按钮时,应该触发一个事件。

我的 Angular 代码块:

<div ng-repeat="q in questionList " ng-if="ExamOver == false">
      <h2>{{count+1}} .{{q.questionText}}</h2>
      <ul>
          <li ng-repeat="d in q.Choices">
              <input type="radio" name="isCorrect" ng-model="correctAnswer.isworking" ng-change="getDetails($index,d,correctAnswer.isCorrect);" value="Yes" />
              {{d.choiceText}}
          </li>
     </ul>
</div>

在我的 Controller 中,我有这段代码:

$scope.correctAnswer = {isCorrect : false};

$scope.getDetails = function (index, choiceList, isCorrect) {    
    /* some logic... */
}

事件每个按钮只触发一次,过去几个小时我一直在努力解决这个问题但没有任何进展,有人可以指导我我在这里做错了什么吗?

最佳答案

ng-change您绑定(bind)的变量的值(使用ng-model)改变时将被触发。在这里,所有单选按钮都具有相同的 value="Yes"。这就是为什么 ng-change 没有被触发的原因。来自 docs :

Evaluate the given expression when the user changes the input. The expression is evaluated immediately, unlike the JavaScript onchange event which only triggers at the end of a change (usually, when the user leaves the form element or presses the return key).

好的解决方案取决于您的需求,但哪里有一些想法:

解决方案1

为您的输入设置不同的值:

<li ng-repeat="d in q.Choices">
     <input type="radio" 
            name="isCorrect" 
            ng-model="correctAnswer.isworking" 
            ng-change="getDetails($index, d, correctAnswer.isCorrect)" 
            ng-value="$index" />
     {{d.choiceText}}
</li>

解决方案2

每当点击 radio 时触发您的功能:

ng-click="getDetails($index, d, correctAnswer.isCorrect)"

关于javascript - 单击列表中的每个单选按钮后 ng-change 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43626992/

相关文章:

javascript - Wordpress:在单击按钮时使用额外的 CSS block

javascript - Blazor:如何包含与 Nuget-Package-Manager 一起安装的 javascript-package?

javascript - 如何自定义 Angular JS UI Bootstrap 日期选择器仅用于选择日期?

angularjs - angular.js $scope.$broadcast, $scope.$emit, $rootScope.$broadcast 用什么?

javascript - 2图像之间的Jquery切换不起作用

javascript - 如何允许使用 Leaflet.draw 编辑要素/多边形?

javascript - AngularJS 中的子菜单(展开/折叠树)

javascript - 为什么 $scope 应用于某些表达式而不应用于其他表达式?

javascript - 在 AngularJS 中过滤多个属性

javascript - angularjs 范围内可以存储的最大数据量是多少?大范围应用程序的性能?