在AngularJS项目中,可以通过以下两种方法从另一个组件中加载数据:
// Service angular.module('myApp').service('dataService', function($http) { var data = {};
this.getData = function() { return $http.get('/api/data').then(function(response) { data = response.data; }); };
this.getDataInService = function() { return data; }; });
// Component A angular.module('myApp').component('componentA', { templateUrl: 'componentA.html', controller: function(dataService) { var ctrl = this;
ctrl.$onInit = function() {
dataService.getData().then(function() {
ctrl.data = dataService.getDataInService();
});
};
} });
// Component B angular.module('myApp').component('componentB', { templateUrl: 'componentB.html', controller: function(dataService) { var ctrl = this;
ctrl.data = {};
dataService.getData().then(function() {
ctrl.data = dataService.getDataInService();
});
} });
// Component A angular.module('myApp').component('componentA', { templateUrl: 'componentA.html', controller: function($scope) { var ctrl = this;
$scope.$on('dataLoaded', function(event, data) {
ctrl.data = data;
});
} });
// Component B angular.module('myApp').component('componentB', { templateUrl: 'componentB.html', controller: function($http, $scope) { var ctrl = this;
ctrl.loadData = function() {
$http.get('/api/data').then(function(response) {
$scope.$broadcast('dataLoaded', response.data);
});
};
ctrl.loadData();
} });