AngularJS Factory HTTP Variable Only Usable in View - angularjs

So, my AngularJS Factory looks like:
.factory('getCategories', function($http) {
return $http.get('api/categories');
})
Then, in the controller, I am getting the value like this:
getCategories.
success(function(data) {
$scope.category_data = data;
});
In the view, I can access the scope variable via {{ category_data }}, and it works fine, returns JSON. But, when I try to access the variable in the controller, it just is always empty. I tried doing this:
$scope.category = $scope.category_data;
Then, after I had that, I would try to access the $scope.category variable in the view via {{ category }}, and it would be blank.
Any tips on an alternative to what I'm doing? Or what I have done wrong?
EDIT: Here is what my whole controller looks like.
.controller('ForumController', function($scope, $route, $routeParams, $location, $filter, getCategories) {
getCategories.
success(function(data) {
$scope.category_data = data;
});
$scope.category = $scope.category_data;
})

Because the success callback is asynchronous, it is being executed AFTER the assignment to $scope.category, so you're actually assigning a value of undefined to $scope.category.
You need to do something like this:
.controller('ForumController', function($scope, $route, $routeParams, $location, $filter, getCategories) {
getCategories.
success(function(data) {
$scope.category = data;
});
})

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.

TypeError: $http.get is not a function in Angular JS

I am trying to use Angular Service and since $scope can not be injected inside service so using $rootScope. My code look like fine but getting following error-
TypeError: $http.get is not a function
Here is code-
EmployeeService.js:
///
app.factory('fetchEmpService', ['$rootScope', '$http', function ($http, $rootScope) {
var employees = [];
return {
fetchEmp: function () {
debugger;
return $http.get("EmpWebService.asmx/GetEmp")
.then(function (response) {
employees = response.data;
$rootScope.$broadcast('allEmployees', employees);
return employees;
});
}
};
}]);
In my controller I am trying to consume it like below:
$scope.employees = fetchEmpService.fetchEmp();
$scope.$on('allEmployees', function (events, employees) {
$scope.employees = employees;
});
I am bit confuse that will the data will come inside $scope.$on
Your parameters and array of injectables are in a different order.
This:
app.factory('fetchEmpService', ['$rootScope', '$http', function ($http, $rootScope)
Needs to be
app.factory('fetchEmpService', ['$rootScope', '$http', function ($rootScope, $http)
The order is important and needs to be the same.
More information on dependency injection.

share data between functions inside controller in Angular

I need to build a url using info from different controllers. inside my post controller I get the posts data from this:
Post Controller:
Data.get('posts').then(function(data){
$scope.posts = data.data;
});
in the same controller I am getting site wide configs
configFactory.getconfigs().then(function(data){
$rootScope.configs = data;
});
below that I am building a url
$scope.twitterUrl = "http://www.twitter.com?p1=$scope.posts.p1&p2=$rootScope.configs.p2&p3=$rootScope.configs.p3";
to put it all together:
app.controller('postsCtrl', function ($scope, $log, $http, $timeout, Data, Auth, TrackClicksFactory, $uibModal, $filter, $rootScope, configFactory, siteMsgFactory, $confirm) {
Data.get('posts').then(function(data){
$scope.posts = data.data;
});
configFactory.getconfigs().then(function(data){
$rootScope.configs = data;
});
$scope.twitterUrl = "http://www.twitter.com?p1=$scope.posts.p1&p2=$rootScope.configs.p2&p3=$rootScope.configs.p3";
}
I am trying to get the data from both the $scope.posts and $rootScope.configs to build out my url.
I am sure this is easy but I have hit a wall. any help is much appreciated

ANGULARJS how to add fields to a collection?

I've a very simple app in AngularJS that use a full REST (sails) backend.
In my services.js I've declared a resource like
MyServices.factory('Post', ['$resource',
function($resource){
return $resource('/post/:PostId', {}, {
//query: { isArray:true }
});
}]);
then in my controller view I've got
MyControllers.controller('PostEditCtrl', ['$scope', '$routeParams', 'Post', '$location', 'flash', '$http', '$rootScope', function($scope, $routeParams, Post, $location, flash, $http, $rootScope ) {
$scope.post = Post.get({PostId: $routeParams.PostId});
When I save the post, If not present, I want to add a field ($scope.post.owner) to add a relationship in my model, so I use this function:
$scope.savePost = function () {
if ($rootScope.currentUser) {
$scope.post.owner = $rootScope.currentUser;
}
$scope.post.$save({ PostId: $scope.post.id });
$location.path("/post/"+$routeParams.PostId);
};
I've got no errors but, I don't see the new field in the post requests.
So far I try also to use $scope.post.push() but without luck.

Can't access my service in my controller (undefined)

I am trying to create a service to do some AJAX requests.
However, my service keeps getting undefined when I try to do something with it in my controllers. Here is my code.
I have found a lot of examples on here, and I've tried to follow a lot of them but no matter what I do my service keeps getting undefined.
My service:
MyApp.factory('myService', function($http) {
return {
findAll: function() {
return $http.get('/findAll')
.then(function(result) {
return result.data;
});
}
}
});
My Controller:
MyApp.controller('UserController', ['$scope', '$http', 'myService', function($scope, $http, $log, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
}]);
I assume I don't inject it correctly but I can't see whats wrong. I'm fairly new to Angular so..
Any pointers would be appreciated.
Remove $log from the injection. You are currently "naming" the myService service to $log and therefore myService inside the controller is undefined.
MyApp.controller('UserController', ['$scope', '$http', 'myService',
function($scope, $http, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
}]);
2nd solution
To avoid having to "name" the services like this it's acceptable to inject them without naming them.
MyApp.controller('UserController', function($scope, $http, myService) {
// Whatever I do with myService here it gets undefined.
//$scope.test = myService.findAll();
//myService.findAll();
});
Just remember to remove the closing bracket aswell.

Resources