Friday, 5 June 2015

angularjs pass value between controllers


I have another blogger for explaining how to pass value between controllers. But it was only for strings and numbers, not for objects.

The blogger is here:

http://baiduhix.blogspot.co.uk/2014/10/how-to-pass-data-from-one-controller-or.html

Today I am going to explain how to pass objects between controllers:

Two ways:

1, services, because they are singleton, globally singleton.  (or factory)



angular.module('toDo',[])

.service('dataService', function() {

  // private variable
  var _dataObj = {};

  this.dataObj = _dataObj;
})

.controller('One', function($scope, dataService) {
  $scope.data = dataService.dataObj;
})

.controller('Two', function($scope, dataService) {
  $scope.data = dataService.dataObj;
});





angular.module('toDo',[])

.factory('dataService', function() {
  var _dataObj = {};
  return {
    dataObj: _dataObj
  };
})

.controller('One', function($scope, dataService) {
  $scope.data = dataService.dataObj;
})

.controller('Two', function($scope, dataService) {
  $scope.data = dataService.dataObj;
});


2, rootscope

var app = angular.module('mymodule',[]);
app.controller('Ctrl1', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = true;
}]);

app.controller('Ctrl2', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = false;
}]);



No comments:

Post a comment