在我的表单中,Angular正在观看选择框以进行更改,然后使用所选数据加载数据以供以后选择框使用。这种方法很好,除了观察者的初始化之外,Angular不会使用选定的选项(由服务器提供)保留现有数据并立即加载新数据。
<form action="join" method="post" ng-controller="JoinController">
...
<select name="state" ng-model="state">
<option value="">Select...</option>
...data provided on initial load...
</select>
<select name="institution_id" ng-model="institutionId" ng-options="option.id as option.name for option in institutionOptions">
<option value="">{{ defaultInstitutionOption }}</option>
...data provided on initial load...
</select>
...
</form>
Angular控制器......
app.controller('JoinController', function($scope, $http) {
$scope.defaultInstitutionOption = "Select state...";
$scope.$watch('state', function() {
$scope.defaultInstitutionOption = "Loading institutions...";
$http.get('institutions?state=' + encodeURIComponent($scope.state)).success(function(institutions) {
$scope.institutionOptions = institutions;
$scope.defaultInstitutionOption = "Select...";
});
}, true);
}
答案 0 :(得分:0)
$watch
需要2个参数newValue
和oldValue
。对于第一个请求,oldValue
将为null或未定义。
检查类似
$scope.$watch('state', function(newValue,oldValue) {
//Check logic based on newValue and oldValue
}