【问题标题】:ng-checked triggers its function more than onceng-checked 多次触发其功能
【发布时间】:2019-07-20 14:55:03
【问题描述】:

这是视图中的代码:

 <input type="radio" name="tabset" id="tab2" aria-controls="rauchbier"
        ng-checked="switch_tabs()">

这就是控制器中的代码

   $scope.switch_tabs = function(){
        console.log(notification_form_data);
        console.log($('#notification_form').serialize());
        if (notification_form_data != $('#notification_form').serialize() & notification_form_data!= undefined)
        { 
            var alertPopup = $ionicPopup.alert({
            title: 'vs',
            template: 'unsaved data in actions',
            button: 'Done'

        });

    }

当条件 = true 时,警报和 console.log 发生 100 次,如何仅触发 1 次

【问题讨论】:

  • id为notification_form的元素是什么?为什么要将 jQuery 与 AngularJS 混合使用?每当你这样做时,你就是在自找麻烦。
  • 只要ng-checked 指令有一个作为函数的AngularJS 表达式,该函数将在每个摘要循环中被多次调用,直到返回值稳定。它总是至少被调用两次。

标签: javascript angularjs


【解决方案1】:

Why is ng-checked firing twice on page load

ng-checked 是一个布尔值。所以它的意思是像ng-checked="checkbox_checked",当checkbox_checkedtrue 时,它会检查复选框。

您可能希望在单击单选框时使用ng-click 触发您的函数一次。

或者,如果您希望在变量更改时发生某些事情,您可以使用$scope.$watch

$scope.$watch('notification_form_data', function() {
   if (notification_form_data != $('#notification_form').serialize() & notification_form_data!= undefined)
    { 
      var alertPopup = $ionicPopup.alert({
      title: 'vs',
      template: 'unsaved data in actions',
      button: 'Done'
     };
})

或者您可以添加一个ng-model 并使用ng-change,它会在模型​​更改时调用您的函数。如果您只希望在选中单选框时运行警报,您可以检查ng-model 中使用的变量是否为真。

<input type="radio" name="tabset" id="tab2" aria-controls="rauchbier"
        ng-model="radio_checked" 
        ng-changed="switch_tabs()">
$scope.radio_checked = false
$scope.switch_tabs = function(){
        console.log(notification_form_data);
        console.log($('#notification_form').serialize());
        if (notification_form_data != $('#notification_form').serialize() && notification_form_data!= undefined && $scope.radio_checked)
        { 
            var alertPopup = $ionicPopup.alert({
            title: 'vs',
            template: 'unsaved data in actions',
            button: 'Done'

        });

    }

【讨论】:

  • 如何解决这个问题,我应该更改 ng-checked 吗?
  • docs.angularjs.org/api/ng/directive/ngChecked 当您设置 ng-checked 时,如果您传递的语句是真实的,您希望检查复选框。
  • 我想在这种情况下发出警报最好的解决方案是什么?
  • 用户可以点击不是最佳实践的已检查输入
  • 我认为 ng-change 是最好的答案,但它不会触发我不知道为什么的功能
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 2019-06-24
  • 2014-04-10
  • 1970-01-01
  • 2023-03-03
  • 2016-10-22
  • 2016-09-07
相关资源
最近更新 更多