【问题标题】:ng-checked with ng-change is not working [duplicate]使用 ng-change 进行 ng-checked 不起作用 [重复]
【发布时间】:2018-05-11 13:49:05
【问题描述】:

这是我的 angularjs 代码

<label class="switch">
    <input
    type="checkbox"  
    ng-model="question.questionId" 
    ng-change="questionStatusChange(question.questionId,!question.active)" 
    ng-checked="question.active" >
    <span class="slider round"></span>
</label>

ng-change 正在从 unchecked 触发到 checked 状态 但 ng-change="questionStatusChange(question.questionId,!question.active)" 无法从 checked 到 unchecked 状态。

我正在尝试启用或禁用表记录。

$scope.questionStatusChange = function(questionId,status) {
console.log(status);
}

我正在使用这个切换: https://www.w3schools.com/howto/howto_css_switch.asp

【问题讨论】:

  • ng-checked 或 ng-model。对于 ng-model,您可以添加 ng-change。切勿在同一输入上同时使用两者。
  • @PetrAveryanov 在初始循环中我希望它基于该值作为“已检查/未检查”,因此我使用了 ng-checked。能否请您给出代码示例。
  • 为什么要将id 绑定到带有ng-model="question.questionId" 的复选框?在我看来,这应该在 html 中的其他位置,例如 &lt;label&gt;
  • 我不需要 ng-model 但如果没有 ng 更改就无法正常工作,这就是我写的原因

标签: javascript angularjs switch-statement toggle


【解决方案1】:

您的问题是ng-model 和ng-checked 不能一起使用。

您应该可以只使用ng-model,并将其绑定到模型上的boolean 属性。从您的 html 中删除 ng-checked 并使用 ng-model。

编辑: 下面展示了如何使用ng-repeat 创建&lt;input&gt; 列表,其中每个部分在$scope.questions[] 中都有自己的对象。完成后,您可以使用ng-model 并将其直接绑定到questions[i].active。

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

var MyController = function($scope) {

  $scope.questions = [{
    questionId: 1,
    active: false,
    questionText: "First question"
  }, {
    questionId: 2,
    active: true,
    questionText: "Second question"
  }];
  $scope.questionStatusChange = function(currentQuestion) {
    //currentQuestion.active = !currentQuestion.active;
    console.log("Current Question Text: " + currentQuestion.questionText + "\nIs it clicked? " +  currentQuestion.active);
  }
}

app.controller(MyController, "[$scope, MyController]");
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>

<body ng-app="MyApp">
  <div ng-controller="MyController">
    <div ng-repeat="question in questions">
      <label class="switch">
        <input
        type="checkbox"  
        ng-model="question.active"
        ng-change="questionStatusChange(question)" />
        <span class="slider round"></span>
      </label>
    </div>
  </div>
</body>

</html>

【讨论】:

  • 您能否添加另一个复选框,该复选框已在初始时选中,更改时应取消选中
  • @Mrworldwide 我已经更新了我的答案。
  • 你能看到我的答案,一旦它在小提琴中正常工作,但在我的场景中,它最初不起作用,但是当我按预期改变它的工作时,是否有任何其他方法可以检查初始负载。 ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-10
  • 2016-08-17
  • 2018-03-11
相关资源
最近更新 更多