AngularJs params give all objects with one id - angularjs

I want to get a single object from json file using AngularJs params, but it give me all objects.
This is the code I've used,
(function () {
"user strict";
angular
.module("myApp")
.controller("indexCtrl", function ($scope, $http, $routeParams) {
var workId = $routeParams.id;
$http({
url: "data/work.json",
method: "GET",
params: {id: workId}
}).then(function(sitedata) {
$scope.workDetail = sitedata.data;
});
});
})();
Please help me. Thanks

If you're loading a json file it will just return the whole content, you'll have to filter in the then callback:
$http({
url: "data/work.json",
method: "GET"
}).then(function(sitedata) {
var match = sitedata.data.filter(function(item) {
return item.id == workId;
});
if (match.length) {
$scope.workDetail = match[0];
}
});

Related

Web Api & Angular js

I am facing a problem while calling a service using $http.
I am opening an .aspx page using iframe and on the page load i want to call a service which i written in the controller but $http is taking full path of the page and then path of the web api service as shown below.
http://localhost:50802/TST00111CFG/app/DispatchNotify/api/DispatchNotifyService/GetWorkOrders
and i want in the below manner
http://localhost:50802/TST00111CFG/api/DispatchNotifyService/GetWorkOrders
My controller code is like this
dbSrvc.getDatFromService('api/DispatchNotifyService/GetWorkOrders', $scope.workOrder).then(function (result) {
debugger;
});
Please help me out in this.
dnApp.service('dbSrvc', ["$http", "$q", function ($http, $q) {
var getDataService = function (url, val) {
debugger;
var deferObj = $q.defer();
$http({
url: url,
method: 'Get',
data: val
}).then(function (data) {
deferObj.resolve(data);
});
return deferObj.promise;
};
var postDataService = function (url, val) {
debugger;
var deferObj = $q.defer();
$http({
url: url,
method: 'Post',
data: val
}).then(function (data) {
deferObj.resolve(data);
});
return deferObj.promise;
};
return {
getDatFromService: getDataService, //To Get Data From Service
postDataToService: postDataService //To Send Data and Retrieve from Service
}

Send data from one controller to a different controller in different ng-app

I have a controller 'searchCntr' with ng-app = 'homePage'. I want to send data using rootscope to a controller = "HashPageCntr" with ng-app set as 'HashPage'. Can i do this using rootscope? I am new to this. Thanks in advance
var app = angular.module('homePage',[]);
app.controller('searchCntr',function($scope,$http,$rootScope) {
$scope.searchHash =function () {
$http({
method: "POST",
data: {
"search": $scope.search
},
url: "/fetchHashes"
}).success(function (data) {
alert(data);
$rootScope.$broadcast('eventName',data);
window.location.assign("/goTohashPage");
});
}
});
// This is a different controller.
var app = angular.module('hashPage',[]);
app.controller('HashPageCntr',function($rootScope){
$rootScope.$on('eventName',function(event,data){
alert("In hash Page ");
alert(data);
});
});

AngularJS binding service variable to controller

I am a Angular noob and having problems with binding a variable from one of my services to one of my controllers. I have read at least a dozen posts on the subject and nothing seems to be working for me.
Here is the controller:
app.controller('TeamController', ['$scope', '$modal', 'teamService', function ($scope, $modal, teamService) {
$scope.teamService = teamService;
$scope.selectedTeam = null;
$scope.selectTeam = function(teamId){
$scope.selectedTeam = teamService.getTeam(teamId, $scope.login.loginId);
};
}]);
Here is the service:
angular.module('teamService', [])
.service('teamService', function($http, $q){
this.selectedTeam = {teamId:-1, teamName:"Select a team", teamLocationName:"", teamDescription:"", teamManaged:false};
this.userTeams = [];
this.getTeam = function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
var promise = $http({
url: "/url-for-getting-team",
method: "POST",
data: postData
});
promise.success(function (data) {
if (data.status === "success") {
this.selectedTeam = data.response;
return data.response;
}
});
promise.error(function () { //TODO handle getTeam errors
return {};
});
};
this.getSelectedTeam = function(){
return this.selectedTeam;
};
});
And here is the template:
<div class="jumbotron main-jumbo" ng-controller="TeamController">
<h1>{{selectedTeam.teamName}}</h1>
</div>
I have tried binding to the getSelectedTeam function and the service variable itself. Do I need to set up a $watch function in the controller? Any assistance would be greatly appreciated.
EDIT:
I tried turning my service into a factory, which still did not help me, so then I looked at a provider that was properly working that I had already written in the application. I converted my "teamService" into a provider and finally worked like a charm. Thanks for the contributions guys.
Code from my new provider:
angular.module('teamService', [])
.provider('teamService', function () {
var errorState = 'error',
logoutState = 'home';
this.$get = function ($rootScope, $http, $q, $state) {
/**
* Low-level, private functions.
*/
/**
* High level, public methods
*/
var wrappedService = {
/**
* Public properties
*/
selectedTeam: {teamName:"Select a team"},
userTeams : null,
createTeam: function(loginId, name, description, locationName, managed){
var postData = {loginId:loginId, teamName:name, teamDescription:description, teamLocationName:locationName, teamManaged:managed};
var promise = $http({
url: "/create-team-url",
method: "POST",
data: postData
});
return promise;
},
getTeam: function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
var promise = $http({
url: "/get-team-url",
method: "POST",
data: postData
});
promise.success(function (data) {
if (data.status === "success") {
wrappedService.selectedTeam = data.response;
}
});
promise.error(function () { //TODO handle getTeam errors
wrappedService.selectedTeam = {};
});
},
getUserTeams: function(loginId) {
var postData = {loginId: loginId};
var promise = $http({
url: "/team-list-url",
method: "POST",
data: postData
});
return promise;
},
joinTeam: function(teamId, loginId){
var postData = {teamId:teamId, loginId:loginId};
var promise =$http({
url: "/join-team-url",
method: "POST",
data: postData
});
return promise;
},
getSelectedTeam: function(){
return wrappedService.selectedTeam;
}
};
return wrappedService;
};
});
As seen in my edit. I converted my service into a provider and all the changes seem to propagate to the view with no issues. I need to further analyze the difference between the factory, service, and provider in order to gain a higher understanding of what is going on here.
The main issue with the code is the way that promises are used. You can either correct that within the service, or handle it in the controller. As an example of the latter, you can re-write the above as:
Controller Code:
app.controller('TeamController', ['$scope', '$modal', 'teamService', function ($scope, $modal, teamService) {
$scope.teamService = teamService;
$scope.selectedTeam = null;
$scope.selectTeam = function(teamId){
teamService.getTeam(teamId, $scope.login.loginId).then(
function(result){
$scope.selectedTeam = result.data;
},
function(error){
console.log(error);
}
)
};
}]);
Service code:
angular.module('teamService', [])
.service('teamService', function($http, $q){
this.selectedTeam = {teamId:-1, teamName:"Select a team", teamLocationName:"", teamDescription:"", teamManaged:false};
this.userTeams = [];
this.getTeam = function(teamId, loginId) {
var postData = {teamId: teamId, loginId: loginId};
return $http({
url: "/url-for-getting-team",
method: "POST",
data: postData
});
};
this.getSelectedTeam = function(){
return this.selectedTeam;
};
});
You can also handle this in the service itself, but it requires a little more code. The key thing is that the getTeam call is asynchronous and needs to be handled using proper promise constructs.

Angular $resource not working correctly

I am trying to build my first Angular $resource to give my application access to CRUD operations, but for some reason the actions being configured for the resource are not defined when I try to execute a query.
Here is my controller logic:
app.controller('MainCtrl', function ($scope, $http, $resource) {
var Alert = $resource('/WebApi/Alert/:type/:id',
{
systemUpdate: { method: 'GET' },
autoArchive: { method: 'POST', url: '/WebApi/Alert/Template/:type' }
});
$scope.systemUpdate = function (alert) {
var data = Alert.systemUpdate({ type: alert.Status, id: alert.AlertId }); // THIS LINE FAILS
console.log(data);
}
I get an error saying that Alert.systemUpdate is not defined. Am I doing something wrong here when configuring my $resource?
Change the definition of your Alert to
var Alert = $resource('/WebApi/Alert/:type/:id',
{},
{
systemUpdate: { method: 'GET' },
autoArchive: { method: 'POST', url: '/WebApi/Alert/Template/:type' }
});
As mentionned in the documentation of $resource, the order of the parameters is the following:
1) Url
2) The default value of the parameters of the url, since you don't have any default value, you must provide an empty object
3) The actions (systemUpdate & autoArchive here)

Angularjs convert service from $resource to $http

How can I convert the following code service that uses $resource to use $http?
angular.module('myApp')
.factory('MyService', function ($resource) {
var url = "..";
return $resource("", {},
{
'servizio1': { method: "GET", url: basePath },
'servizio2': { method: "POST", url: url, data: {} },
'servizio3': { method: "POST", url: url, data: {} }
}
});
Thanks in advance.
First to your question, try something like:
angular.module('myApp')
.factory('MyService', function ($http) {
var url = "..";
var basePath = "...";
return {
servizio1: function(){ return $http.get(basePath); },
servizio2: function(data){ return $http.post(url, data); }
}
});
Call it with:
var returnValue = (new MyService()).servizio1.then(function(data){...})
But actually you could also use the $resource API and do something like:
angular.module('myApp')
.factory('MyService', function ($resource) {
var url = "..";
return $resource(url,{}, {
saveIt: {
method: 'POST',
params: {url: basePath}
}
});
adn call this with
MyService.get({}, function(data){...});
MyService.saveIt({}, postData, function(){success...}, function(){error...});
Check out AngularJS docs for more

Resources