I am trying to call a scope function inside the controller. My aim is to call the function in the load itself.
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.functionname();
$scope.functionname = function() {}
});
You can directly call the function in controller.
app.controller('customersCtrl', function($scope, $http) {
functionname();
function functionname {
//do something.
}
});
If you are looking to reuse the function outside controller then use Service as controllers are not injectable.
Read johnpapa style guide which shows best practices: https://github.com/johnpapa/angular-styleguide
app.controller('customersCtrl', function(someService) {
var vm = this;
activate();
function activate() {
// Do something.. You can get the data from your service
}
});
Then do your $http in services then inject it in your controller/s.
Best way is to use services:
var app = angular.module('myApp', []);
app.service('SomeService', ['$state', function ($state) {
this.someFunction = function() {
return "some value";
};
}]);
app.controller('customersCtrl', function($scope, $http, SomeService) {
SomeService.someFunction();
});
Related
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.
I have created the service but i am not getting how use this service in my controller.
(function(){
'use.strict';
angular
.module('app.core')
.factory('shareBtwnCtrlr', shareBtwnCtrlrService);
/** #ngInject */
function shareBtwnCtrlrService() {
shareBtwnCtrlr = function($scope, $rootScope){
$scope.value = $rootScope.test;
}
return shareBtwnCtrlr;
}
})();
In the above code $rootScope.test is coming from one controller and now i have to use this $scope.value in another controller using this service. The another controller is like below
(function (){
'use strict';
angular.module('app.product')
.controller('ProductController', ProductController);
/** #ngInject */
//ProductController.$inject = ['$http', '$location', '$scope'];
function ProductController($http, $location, $rootScope, $scope, $localStorage, $interval, $timeout,$mdDialog, $document, shareBtwnCtrlr){
var vm = this;
}
})();
You got two modules, so dependency injector can't inject your service from app.core to app.product.
Try to create new module
var app = angular.module('app', ['app.core','app.product']);
and then
angular.module('app').factory('shareBtwnCtrlr', shareBtwnCtrlrService);
Only a service in the same module can be injected to the controllers and directives of the module.
The new module should be added to the app to expand its capabilities.
angular.module('app.core')
.factory('shareBtwnCtrlrService', function() {
var shareBtwnCtrlrService = this;
shareBtwnCtrlrService.value = function(){
//do something
}
return shareBtwnCtrlrService;
}
};
angular.module('app.product')
.factory('productService', function() {
var productService = this;
productService.value = function(){
//do something
}
return productService;
}
};
Now to use the service in the core and product modules, we create app module including both in it
angular.module('app', ['app.product', 'app.core'])
.controller('ProductController', ['shareBtwnCtrlrService', 'productService', function (shareBtwnCtrlrService, productService) {
// ...do something
}]);
I am creating a custom service which logs a user in to my system. In this service, I need to use core services such as $http - How do I actually depend these to be used in my service?
My current code:
.factory('loginService', ['$http', '$rootScope', function() {
var login = function(){
console.log($http);
}
return {login : login};
}])
I call the login function from a controller like so
loginService.login();
I hoped that my console will output the $http object I injected, but it's returning undefined.
How do I access this in the correct way?
You need to add the dependencies to your function arguments:
.factory('loginService', ['$http', '$rootScope', function($http, $rootScope) {
//You can use $http and $rootScope here now
}
See the official docs for more info on Dependency Injection in angular
Services you inject need to be passed as arguments of the function:
['$http', '$rootScope', function($http, $rootScope)
By the way, you'll need to do the same where you're trying to use it:
app.controller(['loginService', function (loginService) {
loginService.login();
});
try this:
var myapp = angular.module('mainApp', []);
myapp.controller('myController', ['$scope', 'myFactory', function($scope, myFactory) {
myFactory.login();
}]);
myapp.factory('myFactory', ['$http', function($http) {
var services = {};
services.login = function() {
console.log($http);
}
return services;
}]);
View:
<div ng-app='mainApp' ng-controller='myController'></div>
I have a controller that updates my awards scope:
Controller 1
.controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {
$scope.updateAwardScope = function () {
resource = TokenRestangular.all('award');
resource.getList()
.then(function (awards) {
$scope.awards = awards;
})
}
}])
Controller 2
I have another controller 2 with a click event thats outside of this controllers scope. Is it possible for the controller below to call the $scope.updateAwardScope function from controller 1?
.controller('MainController', function ($rootScope, $scope) {
$scope.updateAwardScopeClick = function () {
// somehow call function from controller 1
}
});
I've found the use of the factory/service pattern to be a very effective way of reusing code in angular applications. For this particular case you could create an AwardFactory, inject it in your controllers and then call the update function. i.e
AwardFactory
myApp.factory('AwardFactory', ['TokenRestangular', function(TokenRestangular.all) {
var factory = {
awards: []
};
factory.update = function() {
resource = TokenRestangular.all('award');
resource.getList().then(function (awards) {
factory.awards = awards;
});
return factory.awards; // You can skip the return if you'd like that
};
return factory;
}]);
YourController
.controller('MainController', function ($rootScope, $scope, AwardFactory) {
$scope.updateAwardScopeClick = function () {
AwardFactory.update();
}
});
Hope it helps!
You can use angular broadcast and receive
Controller1
.controller("awardController", ['$scope', '$rootScope', 'Restangular', "$q", "$location", "TokenRestangular",
function ($scope, $rootScope, Restangular, $q, $location, TokenRestangular) {
$scope.updateAwardScope = function () {
resource = TokenRestangular.all('award');
resource.getList()
.then(function (awards) {
$scope.awards = awards;
$rootScope.broadcast("update.awards");
})
}
}])
Controller 2
.controller('MainController', function ($rootScope, $scope) {
$rootScope.$on('update.awards', function(){
$scope.updateAwardScopeClick();
});
$scope.updateAwardScopeClick = function () {
// somehow call function from controller 1
}
});
I have 2 controllers defined:
var myApp = angular.module('nestedControllersModule',[]);
myApp.controller('ParentController', ['$scope', function($scope) {
}]);
myApp.controller('ChildController', ['$scope', '$injector', function($scope, $injector) {
$injector.invoke(ParentController, this, {$scope: $scope});
}]);
This gives: ReferenceError: ParentController is not defined.
This code works only if ParentController is defined as:
function ParentController($scope) {}
I am trying to inject the parent in the child as then I can inherit the common functions defined in the parent.
var myApp = angular.module('nestedControllersModule',[]);
myApp.controller('ParentController', ['$scope', function($scope) {
$scope.name = 'ParentName';
$scope.Type = 'ParentType';
$scope.clickme = function() {
alert('This is parent controller "ParentController" calling');
}
}]);
myApp.controller('ChildController', ['$scope', '$injector', '$ParentController', function($scope, $injector, $ParentController) {
$injector.invoke(ParentController, this, {$scope: $scope});
$scope.name = 'Child';
}]);
myApp.controller('ParentController', ['$scope', function($scope) {
}]);
myApp.controller('ChildController', ['$scope', 'ParentController', function($scope, ParentController) {
// ok now you have ParentController
}]);
But I think you need to use Services to share data/functions between Controllers or using PubSub model:
What's the correct way to communicate between controllers in AngularJS?
This reduces coupling between parts of your app.
This is a basic workaround to achieve what you're after:
var myApp = angular.module('nestedControllersModule',[]);
myApp.factory('ParentControllerFactory', function () {
function ParentControllerFactory($scope) {
$scope.name = 'ParentName';
$scope.Type = 'ParentType';
$scope.clickme = function() {
alert('This is parent controller "ParentController" calling');
}
}
return (ParentControllerFactory);
})
.controller('ParentController', ['$scope', '$injector', 'ParentControllerFactory', function ($scope, $injector, ParentControllerFactory) {
$injector.invoke(ParentControllerFactory, this, {
$scope: $scope
});
}])
.controller('ChildController', ['$scope', '$injector', 'ParentControllerFactory', function ($scope, $injector, ParentControllerFactory) {
$injector.invoke(ParentControllerFactory, this, {
$scope: $scope
});
}]);
I say workaround because it's probably worthwhile looking into properly implementing a service to manage any commonality as previously mentioned (or better yet, splitting commonality into directives, clickme for example is a good candidate)
...also note that $injector.invoke(ParentControllerFactory as it is above will most likely chuck a hissy fit if/when you minify your scripts later on, so be careful where and how it used.
Consider using the Mixin pattern possible by using the $controller service.
In your example, you would replace the $injector service with the $controller service:
var myApp = angular.module('nestedControllersModule',[]);
myApp.controller('ParentController', ['$scope', function($scope) {
$scope.name = 'ParentName';
$scope.Type = 'ParentType';
$scope.clickme = function() {
alert('This is parent controller "ParentController" calling');
}
}]);
myApp.controller('ChildController', ['$scope', '$controller', '$ParentController', function($scope, $controller, $ParentController) {
$controller('ParentController',{$scope: $scope})
$scope.name = 'Child';
}]);
This is a good overview of using the $controller service:
http://vadimpopa.com/split-large-angularjs-controllers-using-the-mixin-pattern/