Angularjs将值从一个模块传递到另一个模块

时间:2017-08-14 09:57:53

标签: angularjs

我正在为我的应用程序使用Angularjs,我想在模块之间传输数据,尝试了所有方法,但数据没有通过。请在这里查看我的代码。

  1. 我在frontapp模块中有一个名为departments的页面,在点击特定部门时,我想将部门ID传递给departmentapp模块,其中每个部门都有自己的页面。

    Trigger
  2. Controller的代码

    <a href="./school"><h5>{{school.schoolName}}</h5></a>
    <ul data-ng-repeat="department in school.departments">
    <li data-ng-click="getdepartmentBydepartmentId(department.departmentId);setDepartmentId(department.departmentId)">
        <a href="./department"> {{department.departName}}</a>
    </li>
    
  3. 服务js文件中的代码

    $scope.getdepartmentBydepartmentId = function(departmentId){
        SchoolService.getdepartmentBydepartmentId(departmentId).then(function(response){
            $scope.department= response.data;
        });
    }
    
    $scope.getDepartmentId=function(){
        SchoolService.getDepartmentId().then(function(response){
            $scope.departmentId = response.data;
        });
    }
    
    $scope.setDepartmentId=function(departmentId)
    {
       //Some authentication code...
       alert(departmentId);
       SchoolService.setDepartmentId(departmentId);
       alert(SchoolService.getDepartmentId());
    
       //Here I want to pass the username to homectrl.js
       window.location.href="./department"
    }
    
  4. 在departmentapp模块中 - departmentcontroller.js

    obj.getDepartmentId=function(){
        return departmentIDSchool;
    };
    
    obj.setDepartmentId=function(departmentID){
        // var departmentID = null;
        departmentIDSchool = departmentID;
    };
    
    obj.getdepartmentBydepartmentId=function(departmentId){
        return $http.post('getdepartmentBydepartmentId?departmentId='+departmentId);
    };
    
  5. 但是这里部门我没有得到。在堆栈溢出后经历了很多问题后,我才知道在服务层我们需要有getter和setter,但即使在放置之后它也无法正常工作。有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

您可以在路由器中轻松传递这样的变量

    $routeProvider.when('/:primaryNav/:secondaryNav', {
        templateUrl: 'resources/angular/templates/nav/'+$routeParams.primaryNav+'/'+$routeParams.secondaryNav+'.html'
    });

请参阅templateUrl中的$ routeParams,您也可以将其注入控制器以获取参数。