Sachin HR
Sachin HR

Reputation: 460

Fetching Id from One Controller to Another in angularjs

I have two app.js like frontapp.js and departmentapp.js In school.html which is under SchoolController.js belongs to frontapp.js I am getting all schools and departments by schoolId, when I am clicking on departmentName the page is redirecting to departmenthomepage which is under DepartmentHomeController.js belongs to departmentapp.js can any one suggest me how can I get departmentId when clicked on departmentName

SchoolController.js

$scope.getallschools = function() {
  SchoolService.getallschools().then(function(response) {
    $scope.allschools = response.data;
  });
}

In allschools itself I am getting departments by schoolId

schools.html

<div class="col-xs-12 col-sm-6 col-md-6" data-ng-repeat="school in allschools">
  <div class="row">
    <div class="col-xs-12 col-sm-12 col-md-12">
      <h5>{{school.schoolName}}</h5>
      <ul data-ng-repeat="department in school.departments">
        <li><a href="./department"> {{department.departName}}</a></li> 
      </ul>
    </div>
  </div>
</div>  

DepartmentHomeController.js

$scope.departmentId = 20
DepartmentHomeService.getThemeForDepartment($scope.departmentId)
  .then(function(response) {
  console.log("received theme");
  if(response.data != undefined) {              
    $scope.cssFile = response.data; 
    console.log($scope.cssFile);
    $('head').append('<link rel="stylesheet" type="text/css" media="screen" 
      href='+$scope.csspath + $scope.cssFile +'>'); 
  } else {
    $('head').append('<link rel="stylesheet" type="text/css" media="screen" 
      href='+$scope.csspath + $scope.cssFile +'>'); 
  }
});

Here I hard coded departmentId how can I get departmentId dynamically by clicking on departmentName.

Upvotes: 0

Views: 40

Answers (1)

Hemant Nagarkoti
Hemant Nagarkoti

Reputation: 434

There are many ways to do it. If you are using ui router for managing states and controller you can pass ui-sref="stateName/:id".

Else In your href simply try to changing your url to like

<a href="/department/5">

It will work.

Else you can see how to communicate between two controllers it will help you a lot in understanding how communications happen

What's the correct way to communicate between controllers in AngularJS?

Upvotes: 1

Related Questions