简体   繁体   English

ng-change无法与单选按钮一起使用

[英]ng-change not working with radiobutton

I have a code like this: 我有这样的代码:

<div class="form-group">
    <div class="col-sm-8 col-md-offset-4">
        <label class="ui-radio"><input name="radio1" type="radio" value="A" ng-model="$data.choice" ng-change="onChoice()"><span>A</span></label>
    </div>
</div>
<div class="form-group">
    <div class="col-sm-8 col-md-offset-4">
        <label class="ui-radio"><input name="radio1" type="radio" value="B" ng-model="$data.choice" ng-change="onChoice()"><span>B</span></label>
    </div>
</div>

As you can see, there's a $data.choice ng-model that should trigger a "onChoice()" function when changed, defined at the controller (the ng-controller is defined at the view and works properly). 如您所见,有一个$ data.choice ng模型,该模型在更改时应触发一个“ onChoice()”函数,该函数在控制器上定义(ng-controller在视图上定义且正常工作)。 The problem is that the function doesn't trigger, but if I erase the "$data" and leave it like ng-model="choice" it works perfectly. 问题是该函数不会触发,但是如果我删除“ $ data”并将其保留为ng-model =“ choice”,则它可以完美运行。

$data is just a variable defined by me at the $scope. $ data只是我在$ scope上定义的变量。 I can actually trigger the onChoice() with a button and ng-click, but it doesn't work with the ng-change. 我实际上可以通过按钮和ng-click触发onChoice(),但不适用于ng-change。 I guess it's a problem with ng-change but I don't know what's happening. 我想这是ng-change的问题,但我不知道发生了什么。

Edit 编辑

Ok as I see that it's not that simple, I'll add some information: 好的,因为我看到它并不是那么简单,所以我将添加一些信息:

Here's my controller, It includes some interaction with the $parent controller so I don't know if that could affect: 这是我的控制器,它包括与$ parent控制器的一些交互,所以我不知道这是否会影响:

        $scope.data          = $scope.$parent.data;

        $scope.data.choice = $scope.data.choice || 'vote';
        $scope.onChoice = function(){
            //stuff
        };

I know that logic when initilizing the variable seems strange but that's important, I just simplified the code. 我知道初始化变量时的逻辑似乎很奇怪,但这很重要,我只是简化了代码。 Maybe I could change my logic in order to use just $scope.choice instead of $scope.data.choice, but I still want to know why isn't this working. 也许我可以更改逻辑以仅使用$ scope.choice而不是$ scope.data.choice,但是我仍然想知道为什么这行不通。

Even though the "ng-model" is there, the "onChoice" function is working fine. 即使存在“ ng-model”,“ onChoice”功能也可以正常工作。 Once check your controller logic. 一旦检查您的控制器逻辑。

I wrote a sample program. 我写了一个示例程序。 and check out in the Plunkr 并在Plunkr中签出

angular.module('todoApp', [])
.controller('TodoController', ['$scope', function($scope) {

$scope.onChoice = function(){
  alert("changed.");  
};

}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM