【问题标题】:ng-change not called we ng-model update in promise.thenng-change 不叫我们在 promise.then 中更新 ng-model
【发布时间】:2014-04-10 16:06:54
【问题描述】:

当我更新我的 promise.then 中的 ng-model 参数时,我遇到了未调用 select 中的 ng-change 的问题。我的选择是:

<select ng-model="currentReport"
    ng-options="rpt.ReportDisp for rpt in availableReports" 
    ng-change="updateDependent()"></select>

availableReports 是这些对象的数组,由我的服务中的 $http 调用检索。当通话结束时,我想确保选择第一个条目并执行代码:

webServices.getReports(user, menu1, menu2)
            .then(function (result) {
                $scope.availableReports = result.data.d;
                $scope.currentReport = $scope.availableReports[0];
             }

这会将选择设置为第一个报告,但 ng-change 不会调用函数 updateDependent()。

另外,我尝试在 .then 中添加对 updateDependent() 函数的调用,如下所示。但是当函数被调用时 $scope.currentReport 是未定义的。

webServices.getReports(user, menu1, menu2)
            .then(function (result) {
                $scope.availableReports = result.data.d;
                $scope.currentReport = $scope.availableReports[0];
                updateDependent();
             }

有人知道怎么回事吗?

找到问题了,我

函数更新 updateDependent 被声明为 $scope.updateDependent()。所以我需要将http关联的.then中的引用更改为$scope.updateDependent()。

【问题讨论】:

    标签: javascript angularjs promise


    【解决方案1】:

    我不确定从控制器更新时何时触发 ng-change 的规则,但关于您的其他问题。

    我会修改 updateDependent 以接受这样的参数:

    <select ng-model="currentReport"
        ng-options="rpt.ReportDisp for rpt in availableReports" 
        ng-change="updateDependent(currentReport)"></select>
    

    在你的后端

    webServices.getReports(user, menu1, menu2)
            .then(function (result) {
                $scope.availableReports = result.data.d;
                $scope.currentReport = $scope.availableReports[0];
                updateDependent($scope.currentReport);
             }
    

    我发现最好通过传入参数来更明确地了解函数正在做什么以提高可读性。此外,它还简化了 updateDependent 的测试故事。

    【讨论】:

    • 谢谢。这是一个很好的建议。我之前尝试过它是否可以解决 $scope.currentReport 的原始问题,但它没有效果。我仍然喜欢更明确的想法。
    • 谢谢。您是否确认 $scope.currentReport 已正确填充?
    • Brocco,感谢您指点我再次查看 .then 代码。我发现了这个问题。问题在于“范围”。我应该引用 $scope.updateDependent() 而不是 updateDependent()。
    • 那也行,你没有显示那个代码(不是我会抓住它)
    猜你喜欢
    • 2015-03-08
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 2016-12-09
    • 2014-12-01
    • 2016-12-09
    相关资源
    最近更新 更多