John Doe
John Doe

Reputation: 19

Sharing data between components with the same type in Angular.js 1

I currently have three components of the same type. For example, I have a component called 'Lister' and I have three Lister components that calls different apis (e.g. listing teachers, students and courses). However, if a component that loads courses want to access data from the component that renders teachers then in this case, what should I do? I've seen few ways but they are all related to sharing information between components with other types (via $scope and $rootScope).

  <lister data-ng-cloak api="/teacher" type="teacher"></lister>
  <lister data-ng-cloak api="/student" type="student"></lister>
  <lister data-ng-cloak api="/course" type="course"></lister>

This is the current way to use three components. They share common controller and service.

Upvotes: 0

Views: 740

Answers (3)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27192

In you controller create one object named as lister having properties for each different component :

$scope.lister = {
    "teacherView": "teacher",
    "studentView": "student",
    "courseView": "course",
}

and when you call the setData method, receive the data to be stored and the key, lets say

componentService.setData(data, lister.teacherView)

and update your getData so you can choose which data you want to get like this :

componentService.getData(lister.teacherView)

You can create a service like this:

angular.module('app').service('componentService', function() {
    var d = {};
    function setData(data, key){
        d[key] = data;
    }

    function getData(key){
        return d[key];
    }
})

Upvotes: 0

Vikash Kumar
Vikash Kumar

Reputation: 1718

Create a parent object in controller

var parent={};

Then for all the listers assign value from this parent object so that all your data can be binded to one common object. eg : parent.course=value;

Then they all be sharing data from one common object

Upvotes: 0

Ram_T
Ram_T

Reputation: 8484

APIs may be different in your case but they have a common controller and service. So, declare three arrays to store teachers, students and courses in the service.

app.service('myService', function{
    vm = this;
    vm.teachers = [];
    vm.students = [];
    vm.courses = [];
});

have an api call to get the data.

vm.getApiData = $http.get(url).then(); // url may be to get above three from api

have a function in service to get the lists in to the controller

vm.getData: function(val){
   return vm[val]; // value may be teachers, students and courses
}

Call the above function from the controller.

$scope.teachers = myService.getData('teachers');
$scope.students= myService.getData('students');
$scope.courses= myService.getData('courses');

Now, data is ready. Just access it based on your requirement. Just an idea

Upvotes: 2

Related Questions