我正在尝试根据国家/地区功能countryChange()
执行简单的更改状态。最初,当我在控制器中使用该功能时一切正常,但现在我将该功能转移到服务中,我不太确定在不使用$rootScope
的情况下实现它的最佳方法是什么。请参阅以下内容: -
服务:
angular.module('core').service('FormService', ['$http', function($http) {
var _this = this;
_this.dropdownData = {
countries: {
{
'id': 'cutomeId-001',
'name': 'Austria',
'states': {
{
'state_id': 's1',
'state_name': 'state1',
},{
'state_id': 's2',
'state_name': 'state2',
}
}
}, {
'id': 'cutomeId-002',
'name': 'Australia',
'states': {
{
'state_id': 's1',
'state_name': 'state1',
},{
'state_id': 's2',
'state_name': 'state2',
},{
'state_id': 's3',
'state_name': 'state3',
}
}
}, {
//etc
}
}
}
_this.countryChange = function(countryId) {
_this.dropdownData.countries.forEach(function(value){
if(value.id === countryId) {
// Originally in controller:
// $scope.states = value.states;
// Not sure how to implement this in service
}
});
};
}]);
控制器:
angular.module('core').controller('controller', ['$scope', 'FormService', function($scope, FormService) {
$scope.states = {};
$scope.countryChange = FormService.countryChange;
}]);
HTML:
<select name="country" ng-model="countryModel" id="input-country" class="form-control" required-message="'Country is required.'" ng-change="countryChange(countryModel)">
<option value="">-- Select a country --</option>
<option ng-repeat="country in countries" value="{{country.id}}">{{country.name}}</option>
</select>
<select ng-model="statesModel">
<option ng-repeat="state in states" value="{{state.state_id}}">{{state.state_name}}</option>
</select>
答案 0 :(得分:0)
首先,在您的服务类中,用以下代码替换已注释的if块:
if(value.id === countryId) {
return value.states;
}
现在在您的控制器中:
$scope.countryChange = function(countryModel) {
$scope.states = FormService.countryChange(countryModel);
}
应该适合你