Unable to send data to another controller AngularJS - angularjs

UPDATE PLEASE HELP:
Tried what you suggested, the problem is when i try to pass the value to another "Module". Tried creating a service but the function didn't work, maybe i missed something.
Made Example Using rootScope:
var informes = angular.module('informes', ['angular-drupal', 'ui.bootstrap']);
informes.controller('InformesCtrl', ['drupal', '$rootScope', '$scope', '$http', 'InformesFtry', function(drupal, $rootScope, $scope, $http, InformesFtry) {
$rootScope.nodeID = function(item){
var item = "hi";
console.log(item);
}
}]);
Console hi
It works in first module, but...
In my other Module with different Page...
var nodeInformes = angular.module('node-informes', ['informes']);
nodeInformes.controller('NodeInformesCtrl', ['drupal', '$rootScope', '$scope', '$http', 'InformesFtry', function(drupal, $rootScope, $scope, $http, InformesFtry) {
$scope.nodeID2 = $rootScope.nodeID(item);
console.log($scope.nodeID2);
}]);
Console: item is Undefined
I'm trying to figure out of how can i pass a function to another module, but it seems that it is impossible. I didn't try to use same module, but it works if the controller is child from the first controller.
I really apprecaite any help you can provide me to pass a function with parameter to another module with another controller. I'm trying to learn with this. Thanks!!!
EDIT: If i add the firstcontroller as a dependency it gives me Unknown Provider... Sorry for my mistake.

In Angular JS there are three ways for controllers to communicate with other controllers, and any other method is asking for trouble:
Use a service:
Use a service as an intermediary between controllers:
function MyService() {
this.MyObject = {};
}
function ctrl1(MyService) {
Myservice.MyObject = {
someData: "someValue"
};
}
function ctrl2(MyService) {
$scope.someValue = MyService.MyObject.someData;
}
Use the event system
function ctrl1($rootScope) {
$rootScope.$broadcast("my-event", {someData: "someValue"});
}
function ctrl2($scope) {
$scope.$on("my-event", function(event, params) {
$scope.someData = params.someData;
});
}
Scope inheritence
<div ng-controller="ctrl1">
<div ng-controller="ctrl2">
</div>
</div>
function ctrl1($scope) {
$scope.someData = "someValue";
}
function ctrl2($scope) {
console.log($scope.$parent.someData); //"someValue"
}

Related

Angularjs call a function from a controller to another controller

I'm trying since few hours to call a function from a controller to another controller.
I saw similar topics (I tried but I'm certainly too bad):
What's the correct way to communicate between controllers in AngularJS?
Can one controller call another?
But no concrete example like I'm looking for.
Controllers:
app.controller('Controller1', function($scope, $modal, $modalInstance, job, JobServices) {
$scope.job1 = function () {
JobServices.job1($scope.name)
.success(function(data, status, headers, config) {
// something
});
}
function doSomething(){
// How call test() from controller2 ?
}
}
app.controller('Controller2', function($scope){
function test(){
do a lot of things
}
}
What's the best and easiest way to do that ?
Thank you a lot
EDIT:
I already tried using something like that:
app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope, $modal, $modalInstance, job, JobServices) {
But I have error saying job1 is undefined...
you could the $scope.$emit and $scope.$on, little bit like this
app.controller('Controller1', ['$scope', '$rootScope' function($scope) {
function doSomething(){
$rootScope.$emit("callController2", {});
}
}
app.controller('Controller2', ['$scope', '$rootScope' function($scope) {
$rootScope.$on("callController2", function(){
this.test();
});
function test(){
do a lot of things
}
}

how to passing data from one controller to another controller using angular js 1

hi all i using angular js i need to transfer the value from one page controller to another page controller and get that value into an a scope anybody help how to do this
code Page1.html
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
$scope.Message="Hi welcome"
}]);
now i want to show scope message into page2 controller
var app = angular.module("app", ["xeditable", "angularUtils.directives.dirPagination", "ngNotify", "ngCookies","ngRoute"]);
app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore',
function ($scope, $http, $window, $filter, $notify, $cookieStore)
{
///here i want get that scope value
}]);
You can use $rootScope instead of $scope:
// do not forget to inject $rootScope as dependency
$rootScope.Message="Hi welcome";
But the best practice is using a service and share data and use it in any controller you want.
You should define a service and write getter/setter functions on this.
angular.module('app').service('msgService', function () {
var message;
this.setMsg = function (msg) {
message = msg;
};
this.getMsg = function () {
return message;
};
});
Now you should use the setMeg function in Controller1 and getMsg function in Controller2 after injecting the dependency like this.
app.controller('Controller1', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore', 'msgService',
function ($scope, $http, $window, $filter, $notify, $cookieStore, msgService)
{
$scope.Message="Hi welcome"
msgService.setMsg($scope.Message);
}]);
app.controller('Controller2', ['$scope', '$http', '$window', '$filter','$notify','$cookieStore', 'msgService',
function ($scope, $http, $window, $filter, $notify, $cookieStore, msgService)
{
///here i want get that scope value
console.log('message from contoller 1 is : ', msgService.getMsg());
}]);
You should use services for it .
Services
app.factory('myService', function() {
var message= [];
return {
set: set,
get: get
}
function set(mes) {
message.push(mes)
}
function get() {
return message;
}
});
And in ctrl
ctrl1
$scope.message1= 'Hi';
myService.set($scope.message1);
ctrl2
var message = myService.get()
Sharing data from one controller to another using service
We can create a service to set and get the data between the controllers and then inject that service in the controller function where we want to use it.
Service :
app.service('setGetData', function() {
var data = '';
getData: function() { return data; },
setData: function(requestData) { data = requestData; }
});
Controllers :
app.controller('Controller1', ['setGetData',function(setGetData) {
// To set the data from the one controller
$scope.Message="Hi welcome";
setGetData.setData($scope.Message);
}]);
app.controller('Controller2', ['setGetData',function(setGetData) {
// To get the data from the another controller
var res = setGetData.getData();
console.log(res); // Hi welcome
}]);
Here, we can see that Controller1 is used for setting the data and Controller2 is used for getting the data. So, we can share the data from one controller to another controller like this.

Call a Controller angularjs in another Controller angularjs

Well my problem is I have 2 controllers... and I wanna know whether is possible call any function from them in order to do work them together...
For instance:
firstController.js
angular.module('myApp').controller('FirstController', ['$scope', 'FirstService', function($scope, FirstService) {
function verify(){
//Some operations
}
}]);
secondController.js
angular.module('myApp').controller('SecondController', ['$scope', 'SecondService', function($scope, SecondService) {
function edit(iditem){
//Some operations
//I wanna call here verify() function
}
}]);
Is this possible?
Thanks in advance!
You could do it with only one service and call service from both controllers. This is a basic example, you could add a constructor and pass it $scope for example it depends on what you want to accomplish.
'use strict';
/**
* Service
*/
angular.module('myApp.someService', [])
.factory("someService", function () {
return {
verify: function() {},
edit: function(iditem){
self.verify();
}
});
Then your controllers would look like this:
angular.module('myApp').controller('FirstController', ['$scope', 'someService', function($scope, someService) {
service.verify($scope);
}]);
angular.module('myApp').controller('SecondController', ['$scope', 'someService', function($scope, someService) {
service.edit(iditem);
}]);
Using Prototypical Inheritance
If the controllers are nested:
<div ng-controller="FirstController">
<div ng-controller="SecondController">
</div>
</div>
If the FirstController publishes its functions on $scope, the nested controllers can invoke the functions by prototypical inheritance.
Publish function on $scope:
app.controller('FirstController', function($scope) {
$scope.firstVerify = verify;
function verify(){
//Some operations
}
});
Invoke by $scope inheritance:
app.controller('SecondController', function($scope) {
function edit(iditem){
//Some operations
//I wanna call here verify() function
$scope.firstVerify();
}
});
This will only work if the second controller's scope is a child scope of the first controller's scope.
As you can see, there are many answers to the question. Which answer to use depends on the specific use case.
You can do that through $rootScope controller
include $rootScope in FirstContoller, assign a function:
$rootScope.myFirstController_verify = verify;
And call it from second controller with $rootScope included:
$rootScope.myFirstController_verify();

AngularJS: How to pass arguments to controller when it is registered?

Say I have a controller:
app.controller('HomeCtrl', Com.Xyz.ModuleHome.HomeController);
Com.Xyz.ModuleHome.HomeController is a controller function which has parameters like $scope, $window, $timeout, $http, ... these parameters are injected by AngularJS.
But I want to pass some parameters to the controller when it is registered. This is because my controllers are loaded from different domains by RequireJS, now I want to a controller to know where itself is from.
var myVar = jsFileUrl; // jsFileUrl is provided by RequireJS
// I wish the code looks like below
app.controller('HomeCtrl', Com.Xyz.ModuleHome.HomeController, myVar);
// AngularJS will inject a $controllerContext representing controller itself
function Com.Xyz.ModuleHome.HomeController($controllerContext, $scope) {
$scope.controllerJsFileUrl = $controllerContext.Argument;
}
Is it possible? Maybe there is something I didn't know.
I know a service can do it, but I don't want the controller to depend on a special service name. In the future I may move the controllers to somewhereelse.
Since you are looking for the anti-pattern, you could try using function.bindand pass the argument in the bound function. This will let the value of myVar to be passed in as first argument when the constructor is invoked (everytime).
app.controller('HomeCtrl', Com.Xyz.ModuleHome.HomeController.bind(null, myVar));
var app = angular.module('app', []);
var myVar = 1234;
function Ctrl(myVar, $q, $http) {
console.log(arguments);
}
app.controller('ctrl', ['$q', '$http', Ctrl.bind(null, myVar)]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
</div>
The above approach though short is tricky because you can no longer use controller instance as this as it would not the controller instance anymore instead it would be window. Another way is to create a dummy wrapper for the controller and new up the actual constructor.
.controller('ctrl', ['$q', '$http', function($q, $http) {
return new Ctrl(myVar, $q, $http);
}
]);

Service injection into controller with AngularJS

I have written a service in AngularJS, but I can't get it to work with the angular-seed way of doing things.
The controller code is as follows:
/*function PhotoCtrl($scope, Photo) {
$scope.photos = Photo.query();
}*/
angular.module('myApp.controllers', []).
controller('PhotoCtrl', [function($scope,Photo) {
$scope.photos = Photo.query();
}])
.controller('MyCtrl2', [function() {
}]);
Note that the commented out section works fine, but I would like to handle it somewhat like the (recommended) second way.
The error I get is that Photo is undefined, so my guess would be my method of passing (injecting) it is wrong, but I can't find out how to do it correctly
You need to define the Photo service:
angular.module('myApp.controllers', [])
.service('Photo', ['$log', function ($log) {
return {
query: function() {
// the query code here.
}
};
}])
.controller('PhotoCtrl', ['$scope', 'Photo', function ($scope, Photo) {
$scope.photos = Photo.query();
}])
.controller('MyCtrl2', [function() {
}]);
A couple of references:
http://docs.angularjs.org/api/angular.Module
http://docs.angularjs.org/api/AUTO.$provide#service
In the above sample code I used parameters aliasing, which I suggest in order to avoid issues when minifying your code.
See also an example here:
AngularJS multiple uses of Controller and rootScope
And a Plunker here:
http://plnkr.co/edit/Bzjruq

Resources