我正在尝试为依赖的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()
语句记录“未定义”我对此代码和我正在尝试构建的指令有一些疑问:
scope.states
得到“未定义”?注意: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:
<select
id="common_commonbundle_standard_address_state"
ng-model="common_commonbundle_standard_address.state"
required="required"
ng-disabled="!states"
ng-options="state.name for state in states.entities"
tooltip="Estado"
tooltip-trigger="focus"
tooltip-placement="right"
wv-def="Estado"
wv-cur=""
wv-err="Error!"
wv-req="The value you selected is not a valid choice"
type="text"
class="state ng-scope ng-pristine ng-invalid ng-invalid-required"
var="common_commonbundle_standard_address.country"
disabled="disabled">
</select>
为什么,如果我执行此操作$scope.states = data
且它有值,则选择未启用且未填充值?
答案 0 :(得分:1)
就像提到的评论一样,您需要将控制台日志记录移动到成功回调中。这只是异步请求的本质。
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
的内容