0
我正在嘗試爲從屬選擇元素編寫指令。關係是Country > States > Cities
。當country
類的元素髮生變化時,我應該使用states
類更新元素,類中元素的相同行爲。爲了獲得州我只需要國家編號和城市我需要國家和州編號。所以,我沒有這樣的代碼:從屬選擇元素的AngularJS指令
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
得到「未定義」時JSON帶有值? - 如何訪問其他select元素選擇選項以獲得「城市」?
注:app
是我定義
編輯
我重寫一些代碼,一個角模塊,現在是這樣的指令:
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
並且它有值,那麼select沒有被啓用,並且沒有填充值?
最有可能你的成功的功能做在你的console.log執行。把console.log放在成功/錯誤函數中。 $ http.get返回一個承諾。 –
@MatthewRygiel我做了一些修改並修復了代碼,你能看看我的編輯嗎? – ReynierPM
你可以把你的代碼或plunker或類似的服務,所以我可以看到更多的代碼交互? –