How to transfer $scope.variables to controller?

痞子三分冷 提交于 2019-12-12 00:08:51

问题


I am building a system where i have items listed in a list with variables

  1. Title
  2. Skills
  3. Budget
  4. Posted

I also have a Modal that opens up when i click on an item in the list. I would like to take the current selected item and use its variables in my second modal controller? Is this possible?

I was thinking of using a service where i cache all data that is pulled from database, but then i dont know how i would only display selected item and not EVERY item in the modal.

Here is my controller for the list items:

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();
  };    

}]);

Modal Controller(Where i want to view the Selected Variables):

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

var ctrl = this;

ctrl.closeMe = function () {
  projectsModal.deactivate();
};

}]);

回答1:


Yes you can use variables of one controller inside another controller using two methods

  1. Create Service to communicate between them.
  2. Use $rootScope.$broadcast

sample code

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

    }]);
});

and use it in controller like this:

controller 1

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

controller 2

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



回答2:


//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.
  }



回答3:


With Angular UI modals you can use this:

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;

}]);


来源:https://stackoverflow.com/questions/30934525/how-to-transfer-scope-variables-to-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!