问题
I am building a system where i have items listed in a list with variables
- Title
- Skills
- Budget
- 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
- Create Service to communicate between them.
- 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