Getting Data From Another AngularJS Controller
Solution 1:
have you tried to name the controllers and call them by the name?
<label class="item item-input item-select" data-ng-controller="events as eventsCtrl" >
<div class="input-label">
Group
</div>
<select ng-model="eventsCtrl.groupname" data-ng-controller="groups as groupsCtrl" > <!-- this is in my eventscontroller-->
<option ng-repeat="group in groupsCtrl.groups">{{group.name}}</option><!-- these groups are in GroupsController, this doesn't work -->
</select>
</label>
Solution 2:
If you want to use list of groups created in users controller, then its quite simple...just add each group in a rootScope array. Something like
$rootScope.groupList = []
$rootScope.groupList.push($scope.group) //assuming $scope.group is where use save single group data
Now you can access $rootScope.groupList in any controller and get list groups in any controller by accessing
$rootScope.groupList
but using rootScope is not very good practice. Best way to share data between controllers is services but if you are new to Angular then you can go for rootScope for now but again services are the best way to go for data sharing between multiple controllers.
Solution 3:
You can use a service to share data between your controllers. Services provide an easy way for us to share data and functionality throughout our app.
I'd recommend you to go through this article on how to share data between controllers in AngularJS.
Here is the implementation you can try
<!-- SharedService -->
<script type="text/javascript">
angular.module('myApp')
.service('SharedService', [function () {
var main = {};
main.eventGroupName = '';
main.getEventGroupName = function(){
return main.eventGroupName;
};
main.setEventGroupName = function(groupName){
main.eventGroupName = groupName;
};
return main;
}]);
</script>
<!-- GroupsController -->
<script type="text/javascript">
angular.module('myApp')
.controller('GroupsController', ['$scope', 'sharedService', function ($scope, SharedService) {
$scope.event.groupname = SharedService.getEventGroupName();
// Remaining code for GroupsController
//
//
}]);
</script>
<!-- Eventscontroller -->
<script type="text/javascript">
angular.module('myApp')
.controller('EventsController', ['$scope', 'sharedService', function ($scope, SharedService) {
var groupName = 'Another name';
SharedService.setEventGroupName(groupName);
// Remaining code for Eventscontroller
//
//
}]);
</script>
<!-- View -->
<label ng-controller="GroupsController" class="item item-input item-select">
<div class="input-label">
Group
</div>
<select ng-model="event.groupname"> <!-- this is in my EventsController-->
<option ng-repeat="group in groups">{{group.name}}</option> <!-- these groups are in GroupsController, this doesn't work -->
</select>
</label>
Post a Comment for "Getting Data From Another AngularJS Controller"