【发布时间】:2014-03-06 16:11:10
【问题描述】:
我正在尝试为依赖选择元素编写指令。关系是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() 语句记录“未定义”我对这段代码和我正在尝试构建的指令有一些疑问:
- 为什么当 JSON 带有值时
scope.states会得到“未定义”? - 如何访问其他 select element selected 选项以获取“城市”?
注意: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 并且它具有值,则不会启用选择并且不会填充值?
【问题讨论】:
-
您的 console.log 很可能在您的成功功能完成之前执行。将 console.log 放在成功/错误函数中。 $http.get 返回一个承诺。
-
@MatthewRygiel 我做了一些更改并修复了代码,你能看看我的编辑吗?
-
你能把你的代码或plunker或类似的服务放上来,让我看到你更多的代码交互吗?
-
也看看这个:jsfiddle.net/annavester/Zd6uX 这是你正在尝试做的一个例子。
-
使用指令,您需要让它们能够相互交谈。此外,您的指令很可能需要其中的控制器。该视频展示了如何设置指令之间的通信。希望这会有所帮助。 egghead.io/lessons/angularjs-directive-communication
标签: javascript jquery angularjs angularjs-directive angularjs-scope