Passing Data Between Controllers in Angular Js

Passing data between controllers in Angular JS?

From the description, seems as though you should be using a service. Check out http://egghead.io/lessons/angularjs-sharing-data-between-controllers and AngularJS Service Passing Data Between Controllers to see some examples.

You could define your product service (as a factory) as such:

app.factory('productService', function() {
var productList = [];

var addProduct = function(newObj) {
productList.push(newObj);
};

var getProducts = function(){
return productList;
};

return {
addProduct: addProduct,
getProducts: getProducts
};

});

Dependency inject the service into both controllers.

In your ProductController, define some action that adds the selected object to the array:

app.controller('ProductController', function($scope, productService) {
$scope.callToAddToProductList = function(currObj){
productService.addProduct(currObj);
};
});

In your CartController, get the products from the service:

app.controller('CartController', function($scope, productService) {
$scope.products = productService.getProducts();
});

Passing variables between controllers using AngularJS

Factory is a singleton so it can be used to share data among different controllers or directives. Take a look at the fiddler here. I have created a factory 'sharedContext' which can be used to share any key-value pair across controllers using different $scope.

Factory

myApp.factory("sharedContext", function() {
var context = [];
var addData = function(key, value) {
var data = {
key: key,
value: value
};
context.push(data);
}
var getData = function(key) {
var data = _.find(context, {
key: key
});
return data;
}

return {
addData: addData,
getData: getData
}
});

From the controller that needs to share the object can call the 'addData' method of the factory to store the data under a key. The other controllers/directives which are interested in accessing the shared data can do so by calling the 'getData' method and passing the correct key.

Controller (Sharing Data)

function MyCtrl_1($scope, sharedContext) {
$scope.input_1 = 5;
$scope.input_2 = 15;

$scope.add = function() {
$scope.result = $scope.input_1 + $scope.input_2;
sharedContext.addData("Result", $scope.result)
}
}

Controller (accessing shared data)

function MyCtrl_2($scope, sharedContext) {
$scope.getData = function() {
$scope.result = sharedContext.getData("Result").value;
}
}

The only assumption here is that both the controllers need to use the exact key to share the data. To streamline the process you can use a constant provider to share the keys. Also note that I have used underscore.js to look for the key in the shared context dictionary.

Share data between AngularJS controllers

A simple solution is to have your factory return an object and let your controllers work with a reference to the same object:

JS:

// declare the app with no dependencies
var myApp = angular.module('myApp', []);

// Create the factory that share the Fact
myApp.factory('Fact', function(){
return { Field: '' };
});

// Two controllers sharing an object that has a string in it
myApp.controller('FirstCtrl', function( $scope, Fact ){
$scope.Alpha = Fact;
});

myApp.controller('SecondCtrl', function( $scope, Fact ){
$scope.Beta = Fact;
});

HTML:

<div ng-controller="FirstCtrl">
<input type="text" ng-model="Alpha.Field">
First {{Alpha.Field}}
</div>

<div ng-controller="SecondCtrl">
<input type="text" ng-model="Beta.Field">
Second {{Beta.Field}}
</div>

Demo: http://jsfiddle.net/HEdJF/

When applications get larger, more complex and harder to test you might not want to expose the entire object from the factory this way, but instead give limited access for example via getters and setters:

myApp.factory('Data', function () {

var data = {
FirstName: ''
};

return {
getFirstName: function () {
return data.FirstName;
},
setFirstName: function (firstName) {
data.FirstName = firstName;
}
};
});

With this approach it is up to the consuming controllers to update the factory with new values, and to watch for changes to get them:

myApp.controller('FirstCtrl', function ($scope, Data) {

$scope.firstName = '';

$scope.$watch('firstName', function (newValue, oldValue) {
if (newValue !== oldValue) Data.setFirstName(newValue);
});
});

myApp.controller('SecondCtrl', function ($scope, Data) {

$scope.$watch(function () { return Data.getFirstName(); }, function (newValue, oldValue) {
if (newValue !== oldValue) $scope.firstName = newValue;
});
});

HTML:

<div ng-controller="FirstCtrl">
<input type="text" ng-model="firstName">
<br>Input is : <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{firstName}}
</div>

Demo: http://jsfiddle.net/27mk1n1o/

AngularJS- How to pass data from one controller to another on ng-click()?

You should consider using a service in this case to share the data across your controllers.

SharedService.js

app.service('sharedService', function(){
var categories = [];
names.add = function(incategories){
categories = incategories;
};
names.get = function(){
return categories;
};
});

then inject in your controller1 and controller2 and use depending on your requirement.

 app.controller("TestCtrl", 
function($scope,sharedService) {
$scope.categories =[];
$scope.save= function(){
sharedService.add(yourcat);
}
}
);

and then use it as,

 app.controller("TestCtrl2", 
function($scope,sharedService) {
$scope.getcategories = function(){
$scope.categories = sharedService.get();
}
}
);

AngularJS Service Passing Data Between Controllers

Define your service like this

app.service('userService', function() {
this.userData = {yearSetCount: 0};

this.user = function() {
return this.userData;
};

this.setEmail = function(email) {
this.userData.email = email;
};

this.getEmail = function() {
return this.userData.email;
};

this.setSetCount = function(setCount) {
this.userData.yearSetCount = setCount;
};

this.getSetCount = function() {
return this.userData.yearSetCount;
};
});

Check out Duncan's answer here:

AngularJS - what are the major differences in the different ways to declare a service in angular?

How to pass data from one controller to other controller in AngularJs

Please note that :

setplacementdataValue()
getplacementdataValue()

These are methods and not variables.

So use them as :

setplacementdataValue([Your Array Input]);
console.log(getplacementdataValue());

Note the parenthesis.

Also in your set method, use a different input parameter name.

var app = angular.module("myApp", []);

app.controller('PriorityPlacement', ['myplacementdata',

function(myplacementdata) {

myplacementdata.setplacementdataValue([1, 2, 3]);

console.log(myplacementdata.getplacementdataValue());

}

]);

app.controller('Overview', ['myplacementdata',

function(myplacementdata) {

console.log(myplacementdata.getplacementdataValue());

}

]);

app.service('myplacementdata', function() {

var placementdata = [];

this.getplacementdataValue = function() {

return placementdata;

}

this.setplacementdataValue = function(myplacementdata) {

placementdata = myplacementdata;

}

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">

<div ng-controller="PriorityPlacement">

</div>

<div ng-controller="Overview">

</div>

</div>

How to pass data between controller on different files in Angularjs

See $parent in Angular doc

Declare your modal instance,

 var modalInstance = $modal.open({
templateUrl: '/SomeFolder/FileWithController_3',
controller: 'Controller_3',
scope: $scope.$parent,
});

So you can basically call a method or edit a property from controller_1 in your controller_3.

app.controller("Controller_3", ['$scope', '$http', '$modalInstance',
function ($scope, $http, $modalInstance) {

app.controller("Controller_3", ['$scope', '$http', '$modalInstance',
function ($scope, $http, $modalInstance) {

$scope.SaveSomething = function () {
$http.post(url, obj)
.success(function (data) {
$scope.$parent.modethodToCall(data);
})
.error(function () {});
};
}]);

I think you have to add another $parent because $modal create it's own child $scope. If someone can confirm ?

I personnaly won't recommand to use parent properties/methods. In my projects i create modal instance with params and return an object on modal closure. (See $modal in Angular ui doc)

$modalInstance.close(data);


Related Topics



Leave a reply



Submit