我是棱角分明的新人。我想知道是否可以这样做。我有两个选择元素。一个用于省,一个用于城市。我希望在省更改时更新城市选择元素。我写了两个指令,使用角度服务从服务器获取数据。但我不知道如何说当用户改变省份时该省的变化。实际上我想知道当省指令发生变化时是否可以触发city指令上的事件。 我用Google搜索了这个,但找不到解决方法。任何帮助都提前感谢。 这是我的指示:
省指令
'use strict';
app.directive('province', function (Province, $rootScope) {
return {
restrict: 'E',
replace: true,
templateUrl: "/Templates/Directives/province.html",
link: function(scope, element, attr, controller) {
var elm = angular.element(element);
elm.attr('id', attr['id']);
elm.attr('name', attr['name']);
elm.attr('class', attr['class']);
elm.attr('ng-model', attr['ng-model']);
Province.get().then(function (provinces) {
scope.provinces = provinces;
});
}
};
})
城市指令
'use strict';
app.directive('city', function (City, $rootScope) {
return {
restrict: 'E',
replace: true,
templateUrl: '/Templates/Directives/city.html',
link: function (scope, element, attr, controller) {
var elm = angular.element(element);
elm.attr('id', attr['id']);
elm.attr('name', attr['name']);
elm.attr('class', attr['class']);
elm.attr('ng-model', attr['ng-model']);
City.getByProvince(8).then(function (cities) {
scope.cities = cities;
});
}
};
})
这是我的模板:
province.html
<select>
<option ng-repeat="province in provinces" value="{{province.provinceId}}"> {{province.provinceName}}</option>
</select>
city.html
<select>
<option ng-repeat="city in cities" value="{{city.cityId}}">{{city.cityName}} </option>
</select>
答案 0 :(得分:1)
首先阅读有关如何实施ng-options(http://docs.angularjs.org/api/ng/directive/select)的信息。同时在省选择中添加ng-change。您的代码将更改为:
<select data-ng-model="selectedProvince" data-ng-options="province.provinceId as province.provinceName for province in provinces" data-ng-change="provinceChanged()"></select>
然后在您的省指令的链接功能中,当ng-change触发时触发provinceChanged事件:
scope.selectedProvince = false;
scope.provinceChanged = function(){
if(!scope.selectedProvince){ return; }
$rootScope.$broadcast("provinceChanged", { province: scope.selectedProvince });
};
在你的城市指令中听取这个事件:
scope.$on("provinceChanged", function(event, data){
console.log(data.province); //selected province
});