Reputation: 3790
How do i pass data from the controller to a component to show to the user?
app.js
(function(angular) {
'use strict';
angular.module('app', []).controller('MainCtrl', function MainCtrl($scope, $http) {
$http({
method: 'GET',
url: '/team',
}).then(function successCallback(response) {
console.log(response.data);
this.teams = response.data;
$scope.teams = response.data;
// var keys = Object.keys($scope.agendaEventData);
// $scope.eventslength = keys.length;
}, function errorCallback(response) {
});
}).config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);
})(window.angular);
component
(function(angular) {
'use strict';
angular.module('app').component('bringTeamToEvent', {
templateUrl: '/assets/ng/app/team/bringTeamToEvent.html',
bindings: {
teams: '<'
},
});
})(window.angular);
Template
{{$ctrl.teams}}
{{teams}}
The data is coming from the api no problems, i do not understand the complexity to get it to work. Learning from https://docs.angularjs.org/tutorial/step_13 and https://docs.angularjs.org/guide/component#!
Upvotes: 1
Views: 122
Reputation: 63059
Setting the data on this.teams
is correct, and correct to access it like $ctrl.teams
. The issue here is that your $http
callback functions are injecting their own function context so that this
doesn't refer to the component.
For this reason, it's generally good practice to use arrow functions for callback functions:
$http({
method: 'GET',
url: '/team',
}).then(response => {
this.teams = response.data;
}, response => {
});
Here is a demo
Upvotes: 1