How to inject a controller to a service? - javascript

Normally the service is injected in a controller.
controller.js
angular
.module('myApp')
.factory('myService', function($http){
var myService = {
get: get
};
return myService;
function get(){
// Get function.
}
});
service.js
angular
.module('myApp')
.controller('myController', function(myService) {
myService.get();
});
But it is possible to reverse the way? To Inject a controller to a service?

The straight answer would be No. You don't inject a controller to a service or anywhere else for that matter. The real question is why would you want to do that?
// Update
Assuming you are referring to https://material.angularjs.org/latest/api/service/$mdDialog.
The mdDialog service expects a controller function, you could probably pass it a reference to a function.
Example:
angular.module('app',[])
.factory('myService', function(){
return {
myMdDialogCtrl: function($scope, $mdDialog, items){
// Controller for MD Dialog
}
}
})
.controller('ctrl1', function($scope, $mdDialog, myService){
$mdDialog.show({
...
controller: myService.myMdDialogCtrl
})
})
.controller('ctrl2', function($scope, $mdDialog, myService){
$mdDialog.show({
...
controller: myService.myMdDialogCtrl
})
})

Related

Angularjs read $scope in only root state

I'm using ionic and angularjs.
My app.
.state('auth', {
url: '/auth',
abstract:true,
templateUrl: 'templates/auth.html',
controller: 'authCtrl'
})
.state('auth.reg', {
url: '/reg',
templateUrl: 'templates/register.html',
controller: 'regCtrl'
});
I have this in my auth.html (root view) :
{{authHeader}}
My controller.js
.controller('authCtrl', function($scope, $stateParams) {
// here can get the scope
// $scope.authHeader = "register";
})
.controller('regCtrl', function($scope, $stateParams) {
// here CAN NOT get the scope
$scope.authHeader = "register";
});
Only in root controller I can get the $scope. I want to add another controller called login, and change there to login. Any idea?
You can use $rootScope for this purpose
.controller('authCtrl', function($scope, $rootScope, $stateParams) {
// here can get the scope
// $rootScope.authHeader = "register";
})
And in reg:
.controller('regCtrl', function($scope, $rootScope, $stateParams) {
// here CAN NOT get the scope
$rootScope.authHeader = "register";
});
You can use $rootScope for this purpose
.controller('authCtrl', function($scope, $rootScope, $stateParams) {
// here can get the scope
// $rootScope.headerData.authHeader = "register";
})
And in reg:
.controller('regCtrl', function($scope, $rootScope, $stateParams) {
// here CAN NOT get the scope
$rootScope.headerData = {authHeader : "register"};
});
In your model please use -
{{headerData.authHeader}}
It will always update when controller change.
Try to introduce a Model (a reference object)
$scope.Model = { authHeader : "register" };
That will be inherited by each sub-state and could be changed
usage would be
// {{authHeader}}
{{Model.authHeader}}
See more details here:
How do I share $scope data between states in angularjs ui-router?
or there

Use a service in Angular

I got some problem when I'm trying to use an Angular service in the controlleur of my application.
When I'm trying to use function of my service in my controlleur, my console throw me an error :/
var app = angular.module('app', ['ngRoute'])
app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/login', {
controlleur: 'login',
templateUrl: 'modules/login/login.html'
})
.otherwise({
redirectTo: '/login'
});
}]);
app.service('coreServices', [function () {
this.helloConsole = function () {
console.log("console services");
};
}]);
app.controller('loginController', ['$scope', '$http', '$rootScope', '$location', 'coreServices', LoginController]);
function LoginController($scope, $http, $rootScope, coreServices) {
var vm = this;
vm.helloConsole = coreServices.helloConsole;
vm.helloConsole();
}
angular.js:13708 TypeError: vm.helloConsole is not a function
at new LoginController
I link you this fiddle to show you how I do: https://jsfiddle.net/h8yaxLap/2/
The error throwed is:
angular.js:13708 TypeError: vm.helloConsole is not a function
at new LoginController
Well in your example angular will map $location to coreService in the injected parameters in the function. So I would go for
app.controller('loginController', ['$scope', '$http', '$rootScope', '$location', 'coreServices', LoginController]);
function LoginController($scope, $http, $rootScope, $location, coreServices)
Change service function to return object
app.service('coreServices', function () {
return {
helloConsole: function () {
console.log("console services");
}
};
});
You missed $location parameter for the controller
function LoginController($scope, $http, $rootScope,$location, coreServices)

How do you add a service in Angular so a controller can use it?

I have a basic angular setup. I want to add another factory service so that the mainCtrl can use it.
Here is my controller.js
angular.module('Manalator.controllers', [])
.controller('MainCtrl', ['$scope', function ($scope, manaFactory) {
manaFactory.testString();
}]);
Here is my services.js
angular.module('Manalator.services', [])
.factory('cordovaReady', [function () {
return function (fn) {
var queue = [],
impl = function () {
queue.push([].slice.call(arguments));
};
document.addEventListener('deviceready', function () {
queue.forEach(function (args) {
fn.apply(this, args);
});
impl = fn;
}, false);
return function () {
return impl.apply(this, arguments);
};
};
}])
.factory('manaFactory', [function(){
this.testString = function(){
return 'This works';
};
}]);
Here is my routes.js
angular.module('Manalator', ['ngRoute', 'Manalator.services', 'Manalator.controllers'])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/main.html'
})
.when('/devotion', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/devotion.html'
})
.when('/results', {
controller: 'MainCtrl',
templateUrl: 'partials/pages/results.html'
})
.otherwise({redirectTo: '/'});
});
I get the following error:
TypeError: Cannot read property 'testy' of undefined
at new <anonymous> (controllers.js:3)
at Object.i [as invoke] (main.min.js:1)
at $get.f.instance (main.min.js:2)
at m (main.min.js:1)
at s (main.min.js:1)
at $get.e (main.min.js:1)
at main.min.js:1
at p.$get.p.$eval (main.min.js:3)
at p.$get.p.$apply (main.min.js:3)
at main.min.js:1
It is a cordova phonegap setup with basic routes. I am new to angular. I have looked over the internet and im having trouble setting up a basic service to hold all my data so i can access it from all my routes. Any help would be appreciated.
You will need to identify your services as a dependency of the controller.
The first step is to make sure you define the services before the controller.
then change the controller code so that it names the services as a dependency.
angular.module('Manalator.controllers', ['Manalator.services'])
.controller('MainCtrl', ['$scope', function ($scope, manaFactory) {
manaFactory.testString();
}]);
Hope this helps!

AngularJS - State name passed into controller doesn't work

I'm new to angular and I can't figure out why this isn't working.
When I call {{$state.current.name}} in my view it works perfectly fine, but as soon as I try to pass it to my controller, the state gets "lost".
Here is my setup:
Module:
angular.module('app', ['ui.router'])
.run(function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
})
//followed by boilerplate ui router setup
View:
<home-nav-bar></home-nav-bar>
Directive:
angular.module('app')
.directive('homeNavBar', function () {
return {
restrict: 'E',
templateUrl: 'homeNavBarView.html',
controller: 'navCtrl'
};
})
})();
Controller:
angular.module('app')
.controller('navCtrl', function ($state, $scope) {
alert($state.current.name); //returns empty
});
})();
At this point I am clueless as to why I can get the state name in the view but not in my controller..
Well, ui-router docs say you can access current state's config object using the current property of $state, so there is absolutely no need to attach anything to $rootScope. I have just tested something along the lines of (simplified a bit for readability):
angular.module('myApp')
.controller('SomeCtrl', function ($scope, $state) {
console.log($state.current);
});
The result in Chrome console is:
Object {url: "/some", templateUrl: "app/some.html", controller: "SomeCtrl", name: "some"}
So as you can see all information should be available along with the name.

How does the "main" controller access $routeParams in this example?

I'm experimenting with $routeParams, by following along with this example in the AngularJS documentation. For reference, here is the script itself:
angular.module('ngRouteExample', ['ngRoute'])
.controller('MainController', function($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
})
.controller('BookController', function($scope, $routeParams) {
$scope.name = "BookController";
$scope.params = $routeParams;
})
.controller('ChapterController', function($scope, $routeParams) {
$scope.name = "ChapterController";
$scope.params = $routeParams;
})
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: 'BookController',
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
})
.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: 'ChapterController'
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
What I can't understand is this: how does MainController get the updated $routeParam object? I can see that as I click, items that MainController is responsible for setting are changing, but I don't understand how. It's making it a little tough to reproduce this behavior.
It doesn't get re-instantiated, and it's not "getting" the updated $routeParams object - the object in the controller is the routeParams object. It is the same object that is in the other controllers, not a "copy" of it.
So when the $routeParams object gets changed, the other controller already has the changes.

Categories

Resources