在angularjs中从一个控制器获取Id到另一个控制器

时间:2017-08-01 07:29:32

标签: angularjs

我有两个app.js,如frontapp.js和departmentapp.js 在school.html里面的school.html.js属于frontapp.js我通过schoolId获取所有学校和部门,当我点击departmentName时,页面重定向到DepartmentHomeController下的departmenthomepage.js属于departmentapp.js 任何人都可以建议我如何在点击departmentName

时获得departmentId

SchoolController.js

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

在所有学校本身,我正在按学校划分部门

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 +'>'); 
  }
});

这里我硬编码了departmentId如何通过点击departmentName来动态获取departmentId。

1 个答案:

答案 0 :(得分:1)

有很多方法可以做到这一点。如果您使用ui路由器管理状态和控制器,您可以传递ui-sref =“stateName /:id”。

否则在您的href中,只需尝试将您的网址更改为

<a href="/department/5">

它会起作用。

另外,您可以看到如何在两个控制器之间进行通信,这将有助于您了解通信的发生方式

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