如何将$ scope.variables转移到控制器?

时间:2015-06-19 09:24:23

标签: angularjs angularjs-scope

我正在建立一个系统,我在列表中列出了包含变量的项目

  1. 标题
  2. 技能
  3. 预算
  4. 发布
  5. 当我点击列表中的某个项目时,我还会打开一个模态。我想获取当前所选项目并在我的第二个模态控制器中使用其变量?这可能吗?

    我正在考虑使用一种服务来缓存从数据库中提取的所有数据,但后来我不知道我将如何仅显示所选项目而不是模式中的每个项目。

    这是列表项的控制器:

    app.controller('openProjectsCtrl', ['$scope', '$http', 'projectsModal',
    function ($scope, $http, projectsModal) {
    
      $http.get("http://localhost/app/controllers/php/getProjects.php")
      .success(function (response) {
        $scope.projects = response.projects;
      });
    
      $scope.showModal = function() {
          projectsModal.deactivate();
          projectsModal.activate();
      };    
    
    }]);
    

    模态控制器(我想要查看所选变量):

    app.controller('projectsModalCtrl', ['$scope', '$timeout', 'projectsModal',
    function ($scope, $timeout, projectsModal) {
    
    var ctrl = this;
    
    ctrl.closeMe = function () {
      projectsModal.deactivate();
    };
    
    }]);
    

3 个答案:

答案 0 :(得分:2)

是的,您可以使用两种方法在另一个控制器内使用一个控制器的变量

  1. 创建服务以在它们之间进行通信。
  2. 使用$ rootScope。$ broadcast
  3. 示例代码

    angular.module('myservice', []).service('msgBus', function() {
            this.serviceValue= {};
    
        }]);
    });
    

    并在控制器中使用它:

    控制器1

    angular.module('myservice', []).controller('ctrl1',function($scope, msgBus) {
        $scope.sendmsg = function() {
            msgBus.serviceValue='Hello'; 
       }
    });
    

    控制器2

    angular.module('myservice', []).controller('ctrl2',function($scope, msgBus) {
    $scope.checkValue(){   
    alert( msgBus.serviceValue);
    }
    });
    

答案 1 :(得分:1)

//Html
<div ng-click="listClick()"></div> //this might be list or other.But i take div element here.
//scope
$scope.listClick= function(obj, $event){
    console.log($event.target);
    //Save $event.target element using service and used in next controller.
  }

答案 2 :(得分:0)

使用Angular UI模式,您可以使用:

app.controller('openProjectsCtrl', ['$scope', '$http', '$modal',
function ($scope, $http, $modal) {

   // Open modal for code
   var modalInstance = $modal.open({
     templateUrl: 'modal.html',
     controller: 'projectsModalCtrl',
     resolve: {
        yourObject: function() {
            return $scope.yourObject;
        }
     },
     scope: $scope
   });
});

app.controller('projectsModalCtrl', ['$scope', '$timeout', '$modalInstance', 'yourObject', 
function ($scope, $timeout, $modalInstance, yourObject) {

   $scope.yourObject = yourObject;

}]);
相关问题