1

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#!

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.