依赖选择元素的AngularJS指令

我正在尝试为依赖的select元素编写一个指令。 关系是Country > States > Cities 。 当具有类country元素被更改时,我应该更新具有类states的元素和具有类city元素的相同行为。 要获得州,我只需要国家ID,为了获得城市,我需要国家和州的ID。 所以我做了这个代码:

 app.directive('country', ['$http', function($http) { return { restrict: 'C', link: function(scope, element, attrs) { element.change(function() { $http.get(Routing.generate('states') + '/' + element.val()).success(function(data) { if (data.message) { scope.message = data.message; } else { scope.states = data; } }).error(function(data, status, headers, config) { if (status == '500') { scope.message = "No hay conexión con el servidor."; } }); console.log(scope.states); console.log(scope.message); }); } } }]); 

但是console.log()语句记录“未定义”我对这段代码以及我正在尝试构建的指令有一些疑问:

  1. 当JSON带有值时,为什么scope.states会“未定义”?
  2. 如何获取其他选择元素选择的选项以获得“城市”?

注意: app是我定义的Angular模块

编辑

我重写了一些代码,现在这是指令:

 app.directive('country', ['$http', function($http) { return { restrict: 'C', link: function($scope, element, attrs) { element.change(function() { $http.get(Routing.generate('states') + '/' + element.val()).success(function(data) { if (data.message) { $scope.message = data.message; } else { $scope.states = data; } }).error(function(data, status, headers, config) { if (status == '500') { $scope.message = "No hay conexión con el servidor."; } }); }); } } }]); 

我的模板我有这个HTML:

   

为什么,如果我这样做$scope.states = data并且它有值,select不会启用并且没有填充值?

就像提到的评论一样,您需要将控制台日志记录移动到成功回调中。 这只是异步请求的本质。

1)

  $http.get(Routing.generate('states') + '/' + element.val()).success(function(data) { console.log('success!'); if (data.message) { scope.message = data.message; } else { scope.states = data; } console.log(scope.states); console.log(scope.message); }).error(function(data, status, headers, config) { if (status == '500') { scope.message = "No hay conexión con el servidor."; } }); 

对于2)你会想要使用任何设置为ng-model的东西