1

我有以下内容:

<select data-ng-model="selectedTestAccount" data-ng-options="item.Id as item.Name for item in testAccounts">
   <option value="">Select Account</option>
</select>

有人向我建议,我可以观察这个选择的值是否会随着以下内容发生变化:

$scope.$watch('testAccounts', function(){
  /* get updated values and update other select "model" on success*/
  alert("hello");
});

但这似乎不起作用。一方面,它会在选择出现在屏幕上并且在用户选择任何内容之前立即发出警报。我说我应该注意 selectedTestAccount 的变化是否正确?最后还有一个问题。如何在警报框中显示 selectedTestAccount 的值?

4

2 回答 2

3

如前所述,您可以将其作为第一个参数,无需从范围中获取。利用

$scope.$watch('selectedTestAccount', function(newValue){
  alert(newValue);
});

请注意,您总是将 aundefined作为 a 的第一个更改$watch

于 2013-03-31T15:25:04.073 回答
2

在您的选择中添加“ng-change”怎么样?

在您的示例中,它将是这样的:

<select data-ng-model="selectedTestAccount" ng-change="updateSelectedAccount(selectedTestAccount)" data-ng-options="item.Id as item.Name for item in testAccounts"></select>

然后在你的控制器中

$scope.updateSelectedAccount = function (selectedTestAccount) {
        console.log(selectedTestAccount);
    }

PS对不起,刚刚注意到这个问题有多老了:)希望这可能对将来的人有所帮助。

于 2016-04-28T12:33:32.870 回答