share data between functions inside controller in Angular - angularjs

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

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.

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.

AngularJS Factory HTTP Variable Only Usable in View

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;
});
})

Restangular put method with extra route don't send data

I'm wondering what's wrong with this snippet:
(my goal if send a put request to user/14/account with data to update of course)
.controller('UserAccountCtrl', ['$rootScope', '$scope', '$state', 'user','User','Restangular',
function($rootScope, $scope, $state, user, User, Restangular) {
$scope.user = Restangular.one('user',14).get().$object;
$scope.errors = null;
$scope.save = function(){
$scope.user.one('account').put();
};
}
]);
I've got a call to user/14/account but without data :(
UPDATE
this seems to work
var user = Restangular.one('user',14).one('account');

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