Setting AngularJS global values for accessing and setting across controllers - angularjs

I have been experimenting with AngularJS values, and wish to store a global value for accessing and setting in different controllers.
So I have been trying out with the value approach like so:
var app = angular.module('myApp', []);
app.value('globalValue', 0);
app.controller('myCtrl', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
$scope.updateValue = function() {
globalValue++;
};
}]);
app.controller('myCtrlB', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
$scope.someValueB=globalValue;
}]);
Here's a fiddle
This is not working as I thought it might, so in my fiddle, when clicking the button to increment my 'global', the scope property in myCtrlB does not change.
I have clearly gone about this the wrong way, have I totally misunderstood how to use value()'s here?
Thanks

This code should work basically you need an object so both controllers are pointing at the same object and some property of that object is changed. Otherwise you are assigning the initial value of globalValue to some local variable but it's not a reference.
var app = angular.module('myApp', []);
app.value('globalValue', {counter:0});
app.controller('myCtrl', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
$scope.updateValue = function() {
globalValue.counter++;
};
}]);
app.controller('myCtrlB', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
$scope.someValueB=globalValue;
}]);
Updated fiddle: http://jsfiddle.net/kfxy5hs1/3/

Related

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.

Which one is correct way for initializing module,controller in angularJS?

Which one is correct way for initializing module,controller in angularJS
var myapp=angular.module('myApp', []);
myapp.controller('Ctrl1', Ctrl1);
myapp.controller('Ctrl2', Ctrl2);
Ctrl1.$inject = ['$scope', '$http'];
Ctrl2.$inject = ['$scope', '$http'];
function Ctrl1($scope, $http) {
}
function Ctrl2($scope, $http) {
}
or this way
var myapp=angular.module('myApp', []);
myapp.controller('Ctrl1', Ctrl1);
Ctrl1.$inject = ['$scope', '$http'];
function Ctrl1($scope, $http) {
}
myapp.controller('Ctrl2', Ctrl2);
Ctrl2.$inject = ['$scope', '$http'];
function Ctrl2($scope, $http) {
}
or doing this way
var myapp=angular.module('myApp', []);
myapp.controller('Ctrl1', ['$scope', '$http', function ($scope, $http) {} ]);
myapp.controller('Ctrl2', ['$scope', '$http', function ($scope, $http) {} ]);
I am confusing which way is correct and can you give give me the cirrect project structure of AngularJS frmawork
Any sample project for that in github always welcome
Some peoples says John Papa style which one correct way i mean most efficient way
The simpliest way is to write:
myapp.controller('Ctrl1', function($scope, $http) {
});
And you should use ngmin to parse your code before minification. It will automatically wrap the controller callback in ['$scope', '$http', function($scope, $http) {}] to avoid minification problem.
If you use gulp, use gulp-ngmin.
The second way should be the ideal way as because
It is easy to read.
Easy to maintain
Protected from minification by the injector.
Anyways all of them are correct.
But second way should be the best.
Also make sure that you wrap the code in the way to protect from variable name clashes:
(function(){
'use strict'; //another best practice
//then your code
})()
Angular's $inject method, we can explicitly declare our dependencies. This one may give problem for every controller injection. Other than you can use.
https://docs.angularjs.org/api/auto/service/$injector

AngularJS UI Bootstrap Modal passing object to controller

I'm trying to pass an object to the modal controller with resolve but it doesn't appear to pass correctly. I can console.log the object fine right before I pass it, but trying to log it in the modal controller just shows it is undefined. I've looked at other related questions but I can't see what I'm doing differently from the answers they've been given. Here's my controllers:
app.controller('BlogController', ['$scope', '$http', '$modal', function($scope, $http, $modal){
$scope.blogEntry = {}; // Place holder for data (blog entry)
$scope.editBlogEntry = function(blogEntry) {
$scope.blogEntry = blogEntry;
$scope.editModal = $modal.open({
templateUrl: '/resources/partials/editBlogModal.html',
controller: 'EditBlogController',
size: 'lg',
resolve: {
blogEntry: function() {
console.log($scope.blogEntry); //this shows the object
return $scope.blogEntry;
}
}
});
};
}]);
app.controller('EditBlogController', ['$scope', '$http', '$modalInstance', function($scope, $http, $modalInstance, blogEntry){
$scope.blogEntry = blogEntry;
console.log($scope.blogEntry); //undefined
}])
Can anyone see what I'm missing? Really appreciate the help!
You forgot to add blogEntry as the last string in the array passed to the modal controller.
app.controller('EditBlogController', ['$scope', '$http', '$modalInstance', function($scope, $http, $modalInstance, blogEntry)
HERE ^
Do yourself a favor, and use ng-annotate, which will remove the need for this ugly array syntax, and thus avoid those kinds of bugs.

Can I have two angular.module calls to the same ng-app in two different files for same controller?

Hi I have created two angulerjs files for same ng-app example.
admin.js
var app = angular.module('arcadminmodule', ['ngTable', 'ui-notification']);
app.controller('ArcAdminController', ['$http', '$scope', '$filter', '$interval', 'ngTableParams', 'Notification', function($http, $scope, $filter, $interval, ngTableParams, Notification) {});
admin1.js
var app = angular.module('arcadminmodule');
app.controller('ArcAdminController', ['$http', '$scope', '$filter', '$interval', 'ngTableParams', 'Notification', function($http, $scope, $filter, $interval, ngTableParams, Notification) {});
But its overriding admin.js from admin1.js
please help me out....
In admin1.js when you write:
var app = angular.module('arcadminmodule');
you are not creating a new module. You are trying to get an existing module named 'arcadminmodule'.. If you want to create a new module, you will have to write something like this:
var app = angular.module('arcadminmodule',[]); // add your depencencies...
Now, In your case, in admin.js you are creating your module and admin1,js you are making use of the same module. In angular you cannot have two controllers with the same name. Controllers are for (from the docs):
Set up the initial state of the $scope object.
Add behavior to the $scope object.
So If you need are trying to apply some roles or some business logic, It need to go into one controller. Make sure your controller contain only the business logic needed for a single view.
I think its no need for use the same controller in two places.But you can use services in places.If you need to do some think different from the ArcAdminController,use this structure.
Services
-service1.js
(function (angular) {
angular.module('marineControllers').service('boatService', function (ajaxService) {
}
)
-service2.js
-module..js
var artistControllers = angular.module('marineControllers',['ngAnimate']);
Controllers
-controller1
(function (angular) {
angular.module('marineControllers').controller("BoatController", ['$scope', '$http', '$routeParams',
'dashboardService', '$filter', 'loginService', '$location', 'boatService', 'autocompleteFactory', 'utilityFactory',
function ($scope, $http, $routeParams, dashboardService, $filter, loginService, $location, boatService, autocompleteFactory, utilityFactory) {
function loadAllFishingBoat() {
$scope.boatsTable.length = 0;
if (!$scope.$$phase)
$scope.$apply();
boatService.getAllBoatAndDevice().then(function (data) {
$scope.boatsTable = data;
if (!$scope.$$phase)
$scope.$apply();
});
};
}]);
})(angular);
-controller2
(function (angular) {
angular.module('marineControllers').controller("DeviceController", ['$scope', '$http', '$routeParams',
'dashboardService', '$filter', 'loginService', '$location', 'deviceService', 'autocompleteFactory', 'utilityFactory','commonDataService',
function ($scope, $http, $routeParams, dashboardService, $filter, loginService, $location, deviceService, autocompleteFactory, utilityFactory,commonDataService) {
function loadAllFishingBoat() {
$scope.boatsTable.length = 0;
if (!$scope.$$phase)
$scope.$apply();
boatService.getAllBoatAndDevice().then(function (data) {
$scope.boatsTable = data;
if (!$scope.$$phase)
$scope.$apply();
});
};
}]);
})(angular);
I have been use many services in both controllers,still they are different logics.

A better way to use filters/objects in Angular controllers?

I'm setting a rootScope variable to maintain the state of the program. This works, but I don't think it's quite 'right'. Is there a better way to select an object from an array?
Here's my current code.
angular.module('myApp.controllers', [])
.controller('packingCtrl', ['$scope', '$http', '$filter', '$rootScope', function($scope, $http, $filter, $rootScope) {
$http.get('data/trayData.json').success(function(data) {
$scope.trays = data;
});
var currentOrder = $rootScope.currentlyPacking;;
$http.get('data/orderData.json').success(function(data) {
$scope.orders = data;
$scope.current = $filter('filter')($scope.orders, {orderId: currentOrder});
});
}])
Thanks in advance for any insight / best practices.
You can create a service to hold your state. Each service instance is a singleton, so when the service is injected into various controllers, all will see the same state.
var currentlyPackingSvc = function($http) {
var currentlyPacking = {
}
return {
currentlyPacking: currentlyPacking,
getTrays: function() { /* make $http call and update currentlyPacking */ },
getOrders: function() { /* make $http call and update currentlyPacking */ }
}
}
angular.service('currentlyPackingSvc', ['$http', currentlyPackingSvc]);
angular.controller('packingCtrl', ['$scope', '$http', '$filter', '$rootScope', 'currentlyPackingSvc'
function($scope, $http, $filter, $rootScope, currentlyPackingSvc) {
...
var currentOrder = currentlyPackingSvc.currentlyPacking;
...
}]);
Assuming you leave your 'currentlyPacking' property as an object, the changes should automatically be pushed to your scope.
This way, you have all your state isolated to one service that can be utilized anywhere.

Resources