I'm trying to create a factory and use it cross routes in each controller but apparently I'm doing something wrong...
The app:
var app = angular.module('sam', ['ngRoute', 'ngGrid', 'ui.bootstrap']);
The factory
app.factory("User",function(){
return {};
});
The routes
// configure our routes
app.config(function($routeProvider) {
$routeProvider
// route for the main page which will direct to the buildings page
.when('/', {
templateUrl : 'web/pages/buildings.html',
controller : 'mainController',
controllerAs : 'buildings'
})
});
The controller
app.controller('mainController', ['$filter', '$http','$log', function($filter, $http, $log, User){
$log.log('hello!!!!!', User);
}]);
This prints : hello!!!!! undefined
you are missing 'User' in your controller.
app.controller('mainController', ['$filter', '$http','$log', **'User',** function($filter, $http, $log, User){
$log.log('hello!!!!!', User);
}]);
You forgot to include User as part of injection array
controller('mainController', ['$filter', '$http','$log', function($filter, $http, $log, User){
Should be:
controller('mainController', ['$filter', '$http','$log','User', function($filter, $http, $log, User){
app.factory("User",function(){
return {
show:function(){
alert('Factory called')
}
};
});
app.controller('mainController', ['$filter', '$http','$log','User', function($filter, $http, $log, User){
//that is the way you can call your factory
// you can call this factory function in any controller by injecting it.
User.show(); //will popup alert window.
}]);
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.
My service:
angular.module('app').factory('keretHttpSrv', function ($http, $state, $scope, $rootScope, $q, $localStorage) {
/*some code*/
return keretHttpService;
})
My controller,
angular.module('app.dashboard')
.controller('DashboardCtrl',
['$scope', 'keretHttpSrv', function ($scope, keretHttpSrv)
{
/*some code*/
}])
I have this error:
Error: $injector:unknown provider
How can I solve this problem?
there is no $scope for a factory
FIX
angular.module('app').factory('keretHttpSrv', function ($http, $state, $rootScope, $q, $localStorage) {
/*some code*/
return keretHttpService;
})
You are adding the 'keretHttpSrv' factory to the 'app' module and adding the 'DashboardCtrl' controller to the 'app.dashboard' module. To access the factory you will have to either inject the 'app' module into 'app.dashboard' when you define it
angular.module('app.dashboard', ['app']);
or put both the factory and the controller in the same module
//first define the module
angular.module('app', []);
angular.module('app').factory('keretHttpSrv', function ($http, $state, $scope, $rootScope, $q, $localStorage) {
/*some code*/
return keretHttpService;
})
angular.module('app')
.controller('DashboardCtrl',
['$scope', 'keretHttpSrv', function ($scope, keretHttpSrv)
{
/*some code*/
}])
do you need to use routing here
you have two option :
angular.module("app",['ngRoute']);
it is lib in angular but the second option is better
2.angular.module("app",['ui.router']);
after you need to config the provider of $state in
angular.module("app",['ui.router']).config(function($stateProvider,...){};
all about ui router u can read here UI ROUTER
and see example here Examples
edit: I'm using bootstrap, I think bootstrap tab is causing the
problem
View does not get updated after $scope variable update.
$scope.codeData
if i console the $scope.codeData, i can see the data, but does not render in view.
I have to click twice to get the view render correctly.
is there anything wrong with my code??
Thank you.
config
angular.module('SPAroutes', ['ngRoute', 'SPAcontrollers', 'SPAdirectives'])
.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
.when('/admin', {
templateUrl: 'templates/views/admin.html',
controller: 'adminCtrl',
controllerAs: 'admin'
})
$locationProvider.html5Mode(true).hashPrefix('!');
}]);
Controller.js
angular.module('SPAcontrollers', ['ngRoute', 'SPAfactories', 'SPAdirectives']).controller('adminCtrl', ['$scope', '$http', '$location', '$window', '$SPAaccount', function ($scope, $http, $location, $window, $SPAaccount) {
this.dataRetrive = function(category){
$http.get('/ctrls/get/blockCode/header').then(function (res){
$scope.codeData = res.data;
console.log($scope.codeData);
$('#headerTab').tab('show');
}, function (err){
console.log(err);
})
};
}]);
admin.html
{{codeData}}
You are mixing up controllerAs with scope as phil mentioned in his comment on question. Instead of using scope here store values insidethis reference something like this.
angular.module('SPAcontrollers', ['ngRoute', 'SPAfactories', 'SPAdirectives']).controller('adminCtrl', ['$scope', '$http', '$location', '$window', '$SPAaccount', function ($scope, $http, $location, $window, $SPAaccount) {
var admin = this;
this.dataRetrive = function(category){
$http.get('/ctrls/get/blockCode/header').then(function (res){
admin.codeData = res.data;
console.log(admin.codeData);
$('#headerTab').tab('show');
}, function (err){
console.log(err);
})
};
}]);
and inside the view: admin.html
{{admin.codeData}}
here is working plunk for your refernce
I have an unknown provider error and I'm not sure how to solve it. I think my services, controllers are declared properly. I have tried everything but it doesn't work. my photosFactory factory doesn't work. it's not injected into controller. I'd appreciate any help.
My app.js :
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
my controllers.js :
angular.module('starter.controllers', [])
.controller('PlaylistsCtrl', ['$scope', 'photosFactory', '$http', function ($scope, $http, Util, $ionicLoading, $location, photosFactory) {
$ionicSideMenuDelegate.canDragContent(true);
$scope.allDeals = [];
$scope.navigate = function(url){
$location.path(url);
};
photosFactory.getPhotos().success(function(data){
$scope.allDeals= data;
});
}])
My services.js :
angular.module('starter.services', [])
.factory('photosFactory', function($http) {
return{
getPhotos : function() {
return $http({
url: 'http://www.somecompany.co.uk/bigcapi/feeds/deals/company_id/88',
method: 'GET',
params: {all: '1', mobileready: 1}
})
}
}
})
I think it's because you don't inject $http in your factory.
Try it
.factory('photosFactory', [ '$http', function($http) {
return{
getPhotos : function() {
return $http({
url: 'http://www.somecompany.co.uk/bigcapi/feeds/deals/company_id/88',
method: 'GET',
params: {all: '1', mobileready: 1}
})
}
};
}]);
There is also a problem when declaring your controller
['$scope', 'photosFactory', '$http', function ($scope, $http, Util, $ionicLoading, $location, photosFactory) {
The order is very important so you must have something like this
['$scope', 'photosFactory', '$http', 'Util', '$ionicLoading', '$location', function ($scope, photosFactory, $http, Util, $ionicLoading, $location,) {
Well,
You only declared 3 injectables,
controller('PlaylistsCtrl', ['$scope', 'photosFactory', '$http',
but want to use 6 - that is not good.
function ($scope, $http, Util, $ionicLoading, $location, photosFactory)
Mind the order.
You haven't included your HTML so can't confirm - did you include your services javascript in the index?
Assuming you fix your various import issues, this seems the most likely reason.
Actually you should only declare angular.module('starter.controllers', []) once. You should use angular.module('starter.controllers') instead. (eg. angular.module('starter.controllers', []).controller ...
I cannot get access to methods in my Angular Factory? I get "TypeError: Object # has no method 'method1'" error. My angular app looks like this...
myApp.js
var myApp = angular.module('myAngApp', [])
myApp.config(function ($routeProvider, $httpProvider) {
$routeProvider
.when('/list',
{
controller: 'ListController',
templateUrl: 'partials/list.html'
})
.when('/reports/:reportId',
{
controller: 'DetailController',
templateUrl: 'partials/report.html'
})
})
factory.js
myApp.factory('factory1', function(){
var factory = {};
factory.method1 = function() {
console.log('method1');
}
factory.method2 = function() {
console.log('method2');
}
return factory;
});
ListController.js
function ListController($scope, $location, $http, $route, $rootScope, factory1) {
factory1.method1();
}
ListController.$inject = ['$scope', '$location', '$http', '$route', '$rootScope', 'factory1'];
try this...
myApp.controller('ListController', [
'$scope',
'$location',
'$http',
'$route',
'$rootScope',
'factory1',
function ($scope, $location, $http, $route, $rootScope, factory1) {
factory1.method1();
}]);
instead of your current function ListController and the $inject statement
jsfiddle http://jsfiddle.net/NuCZz/