ANGULARJS how to add fields to a collection? - angularjs

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.

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.

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

How to pass param in routeProvider in Angular JS?

I use routeProvider in Angular JS:
.when('/profile/personal', {
templateUrl: 'personal.html',
controller: 'EditProfileController'
})
How I can pass param to controller EditProfileController and here call Ajax method that returns data. This data must be display in template of route in personal.html.
Example:
.controller('EditProfileController', ['$scope', '$http', function ($scope, $http) {
// If was click on `/profile/personal` from route, must get patam `personal` and call method GetAjax(param);
$scope.GetAjax = function (param){
//here return data put it in template HTML from route
}
}]);
My links are located in page by path:
http://wd.tk/profile
When I click to link route I get URL:
http://wd.tk/profile#/profile/personal/1
Id do:
.controller('EditProfileController', ['$scope', '$http', function ($scope, $http, $routeParams) {
console.log($routeParams);
}]);
I get error:
TypeError: Cannot read property 'idProfile' of undefined
First, in your url configuration, you must put the parameter of url:
when('/profile/personal/:idProfile', {
templateUrl: 'personal.html',
controller: 'EditProfileController'
})
Now, in your EditProfileController, you should get the parameter and call to ajax request:
Inject the $routeParams object and get the parameter with
$routeParams.idProfile:
.controller('EditProfileController',
function ($scope, $http, $routeParams) {
var idProfile = $routeParams.idProfile;
$http.get("service url").then(setData, setError);
function setData(data) {
$scope.data = data;
}
function setError() {
alert("error on get data profile");
}
}]);
In your html, you will show your data profile in the correct format.
But I recommend that all the ajax calls should groups in angular services.
PD:
Check It out angular ui router:
What is the difference between angular-route and angular-ui-router?
hope this helps.
You you need to change your $routeProvider, that should have /profile/:type instead of /profile/personal that means you are going to provide value for :type which can be accessible by injectin $routeParams service inside controller.
.when('/profile/:type', {
templateUrl: 'personal.html',
controller: 'EditProfileController'
})
Controller
.controller('EditProfileController', ['$scope', '$http', '$routeParams', function ($scope, $http, $routeParams) {
$scope.profileType = $routeParams.type;
$scope.GetAjax = function (){
//here you have profile type in $scope.profileType
//you can pass it to ajax by simply accessing scope variable.
$http.get('/getprofiledata?type='+ $scope.profileType)
.success(function(data){
$scope.profileData = data;
})
.error(function(error){
console.log('error occured')
})
}
$scope.GetAjax(); //calling it on controller init
}]);
Update
YOu had missed one of dependency $routeParams in array annotation.
.controller('EditProfileController', ['$scope', '$http', '$routeParams',function ($scope, $http, $routeParams) {
console.log($routeParams);
}]);

: [$injector:unpr] Unknown provider in angularjs can't inject factory into controller

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 ...

AngularJS - Consuming REST API with Restangular in a factory

I understand how to use Restangular in a controller, however my thoughts are that Restangular is essentially an ORM on steroids.
The ORM shouldn't have any knowledge of the state of the application. That is the job of the controller.
I also want to re-use queries to the ORM, and as such, I believe that Restangular should be used inside a service.
My problem is that I am a js / angularjs and restangular noob, having only about 2-3 months exp with anything front-end.
My Controllers:
app.controller('AdminSupplierIndexController',
['$scope', '$stateParams', '$state', 'Supplier',
function ($scope, $stateParams, $state, Supplier) {
$state.reload();
Supplier.getAll.then(function (suppliers) {
$scope.suppliers = suppliers;
});
}]);
app.controller('AdminSupplierDetailController',
['$scope', '$stateParams', 'Supplier',
function ($scope, $stateParams, Supplier) {
Supplier.getOne({ supplierId : $stateParams.supplierID}).then(function(supplier) {
$scope.supplier = supplier;
});
}]);
My Factory
app.factory('Supplier', ['Restangular', function (Restangular) {
return {
getAll: Restangular.all('supplier').getList(),
getOne: Restangular.one('supplier', supplierId).get()
};
}]);
My Supplier.getAll method works fine - I can list all the suppliers from the Supplier factory.
My problem is with my Supplier.getOne method.
Question 1: How do I inject the supplierId into the factory? I am getting ReferenceError: supplierId is not defined
Question 2: Am I trying to over-engineer things considering that I would have to create individual methods for C-R-U-D for every single factory when these methods are already provided by Restangular?
I know this is old, but an alternate way would just be to wrap it within a function. This way, you can keep any other logic within the service/method.
app.factory('Supplier', ['Restangular', function (Restangular) {
return {
getAll: Restangular.all('supplier').getList(),
getOne: function(supplierId) {
return Restangular.one('supplier', supplierId).get()
}
};
}]);
Found the solution in https://github.com/mgonto/restangular#decoupled-restangular-service
Essentially, the way I have solved this problem is as follows:
app.js
$stateProvider
...
.state('admin.supplier', {
url : "/supplier",
templateUrl : 'templates/admin/supplier/index.html',
controller: "AdminSupplierIndexController",
resolve: {
suppliers: ['Supplier', function(Supplier) {
return Supplier.getList();
}]
}
})
.state('admin.supplier.detail', {
url : "/:supplierId",
templateUrl : "templates/admin/supplier/detail.html",
controller: "AdminSupplierDetailController",
resolve: {
supplier : ['Supplier', '$stateParams', function(Supplier, $stateParams) {
return Supplier.one($stateParams.supplierId).get();
}]
}
})
...
Supplier.js
app.factory('Supplier', ['Restangular', function(Restangular) {
return Restangular.service('supplier');
}]);
SupplierControllers.js
app.controller('AdminSupplierIndexController', ['$scope', '$stateParams', '$state', 'suppliers',
function ($scope, $stateParams, $state, suppliers) {
$state.reload();
$scope.suppliers = suppliers;
}]);
app.controller('AdminSupplierDetailController', ['$scope', 'supplier',
function ($scope, supplier) {
$scope.supplier = supplier;
}]);

Resources