以编程方式更改模型时调用ngChange

div*_*ero 11 angularjs angularjs-ng-change

当以编程方式更改模型时调用角度的ng-change时出现问题.

$scope.sendMessage = function() {
    $scope.message = "Message sent";
}

$scope.confirmed = true;
$scope.mySelectBox = $scope.selects[1];

<select ng-model="mySelectBox"
        ng-options="item.name for item in selects track by item.name"
        ng-change="sendMessage()">
</select>
Run Code Online (Sandbox Code Playgroud)

这是代码示例:http://plnkr.co/edit/R4MO86ihMrauHXhpCMxi?p = preview

消息应该为null,因为sendMessage不应该调用.模型以编程方式更改.

kTT*_*kTT 14

您可以尝试使用ngModelOptions.请参阅此plunker以获取参考http://plnkr.co/edit/BdKx62RW5Ls2Iz1H3VR1?p=preview.

在我的例子中,我使用ng-model-options="{ updateOn: 'change', debounce: { change: 0 } }"它似乎工作.它只在我更改选择时运行ngChange中提供的功能.在初始化阶段message保持空白.

  • 将此标记为正确答案,因为您没有被迫修改ng-change调用的函数。谢谢! (2认同)

sam*_*tin 3

根据文档,你是对的。

https://docs.angularjs.org/api/ng/directive/ngChange

但这似乎是由事件连接顺序引起的错误

最好的解决方法 - 求助于 js 处理程序(onchange)

$scope.$watch("mySelectBox", function(a,b) {
    if (a.name!=b.name) {
       $scope.message = "Message sent! (old="+b.name+', new='+a.name+')';
    }
  });
Run Code Online (Sandbox Code Playgroud)

请参阅 plunk http://plnkr.co/edit/2ZbxS1tszppR9SrNqxVB?p=preview

华泰