ng更改函数未被调用,并且没有错误

ng-change function is not being called and no error?

本文关键字:有错误 调用 函数 ng      更新时间:2023-09-26

我正在处理angular中的一个选择框,它似乎从未调用过ng更改函数。这是选择的代码:

<select
    data-ng-options="choice.id as choice.singular for choice in model.doseUnitChoices"
    data-ng-model="ucumId"
    data-ng-change="updateForm()"
    class="form-control input-sm">
    <option value=""></option>
</select>

我已经简化了控制器功能中的代码,以实现所需的最低限度:

  updateForm: function(){
    console.log('test');
  },

到目前为止,一切正常,下拉菜单显示了所有可用的选项,但当我选择下拉菜单中的任何选项时,它会立即变回最后一个选项,这可能意味着什么,并且从未调用更改函数,控制台中也不会出现错误?关于如何调试这个问题并找出问题所在,有什么想法吗?

更新:有趣的是,我在检查页面上的元素时发现,实际上所有的select元素都被列为selected,也许用作模型的数据有问题?查看

我发现问题是由问题范围之外的两个问题引起的:

  1. 调用此select时ucumId不存在,我想这会导致所有select选项都被设置为select
  2. 因为上面的错误导致所有选项都被"选择"了,所以无论我在选择中做了什么,它都从未更新过值,所以没有发生任何变化

无论如何,确保"ucumId"存在解决了我遇到的问题,

我只是试着复制它,用最少的代码量,它工作得很好。

<html>
<body ng-app="app" ng-controller="myController">
    <select 
        data-ng-options="choice as choice.label for choice in model.doseUnitChoices" 
        data-ng-model="ucumId" 
        data-ng-change="updateForm()"
        class="form-control input-sm">
        <option value=""></option>
    </select>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js "></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-animate.min.js "></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-aria.min.js "></script>
    <script>
        angular.module("app",[]).controller("myController", myController)
        function myController($scope) {
            $scope.ucumId = "";
            $scope.updateForm = function(){
            console.log('test');
            };
            $scope.model = {}
            $scope.model.doseUnitChoices = [
                {id: 1, label: "one" },
                {id:2, label: "two" }
            ]
        }
    </script>
</body>
</html>

我怀疑,要么是某个地方有一个小的拼写错误,要么是updateForm在某个地方被重新定义,要么是您的控制器在某个位置被重新定义。我建议把实际的代码配对,然后一块一块地删除,直到它发挥作用或类似的东西。