AngularJS: how should I set the params for $http dynamically? - javascript

I am very new with AngularJS. Thank you for answer. My code is as follow:
mainModule.controller('MainController', function($scope, $http) {
$http.get('http://localhost/backend/WebService.php', {params: {entity: 'IndexPageEntity'}}).
success(function(data) {
$scope.intro = data[0].IndexPageContent;
});
$http.get('http://localhost/backend/WebService.php', {params: {entity: 'ExhibitionServiceEntity'}}).
success(function(data) {
$scope.exhibit = data[0].ExhibitionServiceContent;
});
$http.get('http://localhost/backend/WebService.php', {params: {entity: 'ShootingServiceEntity'}}).
success(function(data) {
$scope.shooting = data[0].ShootingServiceContent;
});
});
My html file would be:
<div ng-controller="MainController">
<div>{{intro}}</div>
<div>{{exhibit}}</div>
<div>{{shooting}}</div>
</div>
I believe there must be some ways to improve the above code in order to reduce repetition. What I want is to pass entity parameter to the controller on creation.
Using ng-init to pass parameter is discouraged, according to the documentation. Writing custom directive to pass argument to scope does not work since parameters would be overwrittern.
What is the best practice to set params dynamically for use in $http? Thank you.

You should move all the logic to a service and use a directive. I would suggest you to modify your backend to return the same structured data, instead of IndexPageContent, ExhibitionServiceContent, etc. it should be Content or whatever name you want to use. But for now I've added a replace function to get the name of the content from the name of the entity.
mainModule.factory('webService', function($http) {
var apiUrl = 'http://localhost/backend/WebService.php';
function getContent(params) {
var config = {
'params': params
};
return $http.get(apiUrl, config);
};
return {
getContent: function(params) {
return getContent(params)
}
};
});
mainModule.controller('MainController', function($scope, webService) {
var params = {
'entity': $scope.entity
};
var contentName = $scope.entity.replace('Entity', 'Content');
webService.getContent(params).then(function (data) {
$scope.content = data[0][contentName];
});
});
mainModule.directive('EntityContent', function() {
return {
controller: 'MainController',
replace: true,
restrict: 'E',
scope: {
entity: '#entity'
},
template: '<div>{{ content }}</div>'
};
});
<div>
<entity-content entity="IndexPageEntity">
<entity-content entity="ExhibitionServiceEntity">
<entity-content entity="ShootingServiceEntity">
</div>

Create an object data and send the value for the key inside the object at every call.. Also pass the value for key to be set inside the scope..
E.g.
$scope.makeHttpCall = function(data) {
$http.get('http://localhost/backend/WebService.php', {params: data}).
success(function(data) {
$scope[$scope.key] = data[0][$scope.key];
});
};
you can then call this function as
$scope.key = 'IndexPageContent';
data = {
entity : 'yourValueHere'
};
$scope.makeHttpCall(data);
You can set other values as well inside the scope that are dynamic for each request..
I hope this makes sense to you...

Related

How to make $scope value in another controller update when calling function inside factory?

I'm having 2 controller placed on a same page and using a same factory. All things i want is when a function in controller 1 execute, it will call to the function inside factory then the $scope in controller 2 will be update its value. When page is loaded controller can get the list but after controller 1 call the factory, nothing was changed, no any call to server...
Here is Controller 1:
app.controller('controller1', function ($scope, $http, globalServices) {
$scope.createFuntion = function(){
$http.post(url, $.param(some_object)).then(function(response){
//Handle something ...
globalServices.userList();
});
}});
Here is Controller 2:
app.controller('controller2', function ($scope, $http, globalServices) {
$scope.users = globleServices.userList();});
Here is factory:
app.factory('globalServices', function ($http) {
return{
userList: function(){
var users_data = [];
$http.get(url).then(function (response) {
var res = response.data;
if (res.status === 200) {
angular.forEach(res.data, function (staff) {
users_data.push(staff);
});
} else {
alert('Oops! Somethings went wrong!');
}
});
return users_data;
}
}});
There is a thing in the AngularJs space and JavaScript in general referred to as the dot rule. If you have a property on an object like
service.data
when you assign that to another object
$scope.data = service.data;
It assigns a reference to the object and now if you update the service the controller does not know about the new data.
Using the dot rule you can have an object on the service that holds data objects
service.data = {};
this object should never change reference to a new object and always be the same instance and you can add new properties to it
service.data.userList = response.userList;
Now if you assign the data in the service to the scope
$scope.data = service.data;
and in the template use
<div ng-repeat="user in data.userList">{{ user.name }}</div>
Userlist will be updated when the service updates the userList.
You should never inject $http into controllers, you should only inject services into controllers and have services make http calls. Injecting $scope is an outdated method of doing AngularJs, you are following outdated tutorials and should look into using the controllerAs syntax or use components that wrap the controllerAs syntax with an Angular 2 style of development.
Create an object in your factory that will somehow serve as a state then create a getter for it. Separate your fetch function and getUserList. See the modified code below.
app.factory('globalServices', function ($http) {
var list = {
users_data: []
}
return{
getUserList: getUserList,
fetchUserList: fetchUserList
}
function getUserList() {
return list;
}
function fetchUserList() {
list.users_data = [];
$http.get(url).then(function (response) {
var res = response.data;
if (res.status === 200) {
angular.forEach(res.data, function (staff) {
list.users_data.push(staff);
});
} else {
alert('Oops! Somethings went wrong!');
}
});
}
});
Now in your controller1
app.controller('controller1', function ($scope, $http, globalServices) {
$scope.createFuntion = function(){
$http.post(url, $.param(some_object)).then(function(response){
//Handle something ...
globalServices.fetchUserList();
});
}});
and in your controller2
app.controller('controller2', function ($scope, $http, globalServices) {
$scope.users = globalServices.getUserList();
});
Now your $scope.users listen to every change in your user_data.
Access the array thru $scope.users.users_data

Update ng-repeat after ng-resource call is finished

I am using ngResource in combination with ng-repeat and noticed that slow REST calls doesn't update the list properly. It keeps empty.
As far as I understood I need a binding between controller and ng-repeat element.
My resource and controller definition:
(function (configure) {
configure('loggingResource', loggingResource);
function loggingResource($resource, REST_CONFIG) {
return {
Technical: $resource(REST_CONFIG.baseUrl + REST_CONFIG.path + '/', {}, {
query: {
method: 'GET',
isArray: true
}
})
};
}
})(angular.module('loggingModule').factory);
(function (configure) {
configure('logController', logController);
function logController(loggingResource) {
var that = this;
loggingResource.Technical.query(function (data) {
that.logs = data;
});
//that.logs = loggingResource.Technical.query();
}
})(angular.module('loggingModule').controller);
ng.repeat usage:
<tr class="table-row" ng-repeat="log in logController.logs">
What I have tried so far:
ng-bind in combination with ng-repeat
$q with deferrer
$promise of ngResource
What did I miss?
My try to get it on plnkr: https://plnkr.co/edit/t1c5Pxi7pzgocDMDNITX
The {{}} provides a default binding between your controller and view and you don't need to add anything explicitly. I have updated your plunkr with some minor changes to injected constants etc. and it is working.
// Code goes here
angular.module("loggingModule", ['ngResource']);
(function(configure) {
configure('loggingResource', loggingResource);
function loggingResource($resource) {
return {
Technical: $resource('https://api.github.com/users/addi90/repos', {}, {
query: {
method: 'GET',
isArray: true
}
})
};
}
})(angular.module('loggingModule').factory);
(function(configure) {
configure('logController', logController);
function logController(loggingResource) {
var that = this;
that.logs = [{
title: 'test2'
}];
loggingResource.Technical.query(function(data) {
that.logs = data;
});
//that.logs = loggingResource.Technical.query();
}
})(angular.module('loggingModule').controller);
Since the api resource was not working, I have used my github repo api link there
The updated working plunkr is available here: https://plnkr.co/edit/cederzcAGCPVzc5xTeac?p=preview
Try to use
that.logs.push(data)
so you prevent to reinitialise the logs list. If you override the logs list and the ng-repeat is initialised before the logs list it seems to not be resolved.
Your logs list is set correctly after the rest call?

AngularJS - DRY two-way data-binding using controllerAs syntax and service properties

I've stumbled upon a problem that should be common and obvious but I can't seem to wrap my head around it.
I'm working on a small prototype app. My backend developer provides me with profile data in a JSON object. Let's say, it looks like this:
profile = {Name: 'John', Email: 'john#mail.com', DOB: '1980-11-03'}
I need these values in multiple locations and I also don't want to put backend http calls in the controllers, so I've created a service to handle this:
angular.module('app', [])
.service('ProfileService', ['$http', function ($http) {
var service = this;
service.Name = null;
service.Email = null;
service.DOB = null;
service.getProfile = function () {
return $http.get('/profile').then(function (response) {
service.Name = response.data.Name;
service.Email = response.data.Email;
service.DOB = response.data.DOB;
return true;
});
};
return service;
}])
.controller('ProfileCtr', ['ProfileService', function (service) {
var vm = this;
service.getProfile().then(function () {
vm.Name = service.Name;
vm.Email = service.Email;
vm.DOB = service.DOB;
});
}]);
There are a number of problems with this solution:
Since the profile data consists of primitives, directly binding to the service properties won't give automagically synchronization of data.
More importantly, it breaks the DRY concept, as I've written data declarations in at least 3 different places (the database schema, in getProfile() and in the controller).
One solution would be to add a layer of indirection and create an object within the service:
angular.module('app', [])
.service('ProfileService', ['$http', function ($http) {
var service = this;
service.profile = {};
service.getProfile = function () {
return $http.get('/profile').then(function (response) {
for (key in response.data) {
service.profile[key] = response.data[key];
};
return true;
});
};
return service;
}])
.controller('ProfileCtr', ['ProfileService', function (service) {
var vm = this;
service.getProfile().then(function () {
vm.profile = service.profile;
});
}]);
This works in general, but now I get awkward controllerAs syntax:
<div ng-controller="ProfileCtr as ctr">
<h1> {{ ctr.profile.Name }}</h1>
<p> Email: {{ ctr.profile.Email }} <br /> DOB: {{ ctr.profile.DOB }}</p>
</div>
I'm wondering whether there is a way that gives me both: clean HTML {{ ctr.Name }} syntax and
a DRY programming style.
Thanks for any hints!
I have a feeling that you want more than this, but this to me is at least DRY:
angular.module('app', [])
.service('ProfileService', ['$http', function ($http) {
var service = this;
service.getProfile = function () {
return $http.get('/profile').then(function (response) {
return response.data;
});
};
return service;
}])
.controller('ProfileCtr', ['ProfileService', function (ProfileService) {
var vm = this;
ProfileService.getProfile().then(function (profile) {
vm.profile= profile;
});
}]);
The service gets the data. You could add functionality for caching here too. The controller uses the service to get the data. There is no repeated code.
I like to use the $scope variable, which would remove the one-layer of indirection issue. However, the controllerAs does have it's advantages, particuarly if you are using nested controllers and want to make it clear which controller you are using. And the $scope identifier will be removed in version 2.
Using a directive for this section of html instead of a controller should make you code easier to read and re-use. It also is advised to make it ready to be upgraded to version 2.
Then:
app.directive('isolateScopeWithControllerAs', function () {
var controller = ['ProfileService', function (ProfileService) {
var vm = this;
ProfileService.getProfile().then(function (profile) {
vm.profile= profile;
});
}];
return {
restrict: 'EA', //Default for 1.3+
controller: controller,
controllerAs: 'vm',
bindToController: true, //required in 1.3+ with controllerAs
templateUrl: // path to template
};
});
Then your HTML still gives you:
<h1> {{ vm.profile.Name }}</h1>
<p> Email: {{ vm.profile.Email }} <br /> DOB: {{ vm.profile.DOB }}</p>
The ProfileCtr as vm would come into more use if you were using the directive for more than one object. For example, if you has a user directive, then you could have:
controllerAs: 'user',
with user.profile.name and ng-repeat='friend in user.friends' etc.

Angular wp-api cannot get headers for X_Total_Pages

I'm using Angular wp-api module and each time my $resource request responds I can see the ResponseHeaders in Chrome with X_Total_Pages and other header information. But I cannot add them to the scope.
Here is my controller...
.controller('newslettersController', ['$scope','$stateParams','$sce','WPFactory', function ($scope,$stateParams,$sce,WPFactory) {
$scope.newsletters = WPFactory.query({
param1: 'posts',
page: $scope.pageNum,
'filter[cat]': 8,
'filter[posts_per_page]' : 10,
'filter[orderby]': 'ID'
}, function(data, reponseHeaders) {
$scope.header = reponseHeaders('X_Total_Pages');
});
});
}]);
And my factory...
.factory("WPFactory", function($resource) {
var dataResponse = $resource('http://www.example.com/wp-json/:param1/:param2/:param3/:param4/:param6/:param7', {}, {
get: {
method: 'GET'
}
});
return dataResponse;
})
is this jeffsebrings angular module? If it is I think you need to inject your service with wpAPIResource:
.factory("WPFactory", function($resource, wpAPIResource)
and use it to query the json rest api (wp-api).
Also, not sure if your controller is passing the query object quite right:
I would change up your factory something like this:
.factory("WPFactory", function(wpAPIResource) {
var posts_query = function(args) {
return wpAPIResource.query(args);
};
return posts_query;
})

AngularJS second query not hitting service

I currently have a factory that looks like this:
ChecklistApp.factory('Api', ['$resource', function ($resource) {
return {
Checklists: $resource('api/checklists', {}, { 'query': { method: 'GET', isArray: false } }),
Checklist: $resource('api/checklist', {}, { 'query': { method: 'GET', isArray: false } }),
AddChecklist: $resource('api/addchecklist', {}, { 'query': { method: 'POST' } }),
UpdateChecklist: $resource('api/updatechecklist', {}, { 'query': { method: 'PUT' } })
};
}]);
I have two controllers that use this factory
a list controller - which lists all checklists
an update controller - which displays one checklist and allows its detailed to be modified
The list controller assigns the data to a variable which in turn is bound to the UI as follows:
$scope.search = function () {
Api.Checklists.query({ Name: $scope.searchName },
function (data) {
$scope.checklists = data.checklists;
}
);
};
In my edit controller I have the following update function which successfully updates the data in the DB and returns the user to the home (list) page.
var EditCtrl = function ($scope, $location, $routeParams, Api) {
$scope.action = "Update";
var id = $routeParams.editId.replace(/\D+/, '');
Api.Checklist.query({ id: id },
function (qd) { $scope.item = qd.checklist; }
);
$scope.update = function () {
Api.UpdateChecklist.save({ Id: $scope.item.id, Name: $scope.item.name },
function (data) {
$scope.item = data.checklist[0];
$scope.$apply();
$location.path('/#'); //Return to list controller
}
);
}
My issue is that after data is modified in my edit controller, I navigate back to the list control and although it hits the search query in the javascript it does not hit the service endpoint on the second call (skips it altogether) and the data is not refreshed (so the modified checklist has been updated on the DB but in the view on list control is remains as it was).
So my question is
How can I forcefully load the data again from the db using the same query that was run to load data initially ($scope.search in list control >> why does it skip this when the page is navigated to for the second time?) and/or alternatively is there a better way to just share the collection over multiple controllers (I read about nesting the scopes and putting the collection in the parent scope which could be accessed by both controllers but not sure if this is best practice or a suitable solution?)
Thanks

Categories