AngularJS modalpopup Service call Cannot read property of undefined - angularjs

I got an issue with Angular JS popup. I am submitting the data from the popup and I want to pass the data to a taskService so that it can call a WebAPI and store on to my DB.
This is my Call from BoardCtrl to open the Modal window
$scope.showAddTask = function () {
modalService.showModal({
templateUrl: "Partials/AddTask.html",
controller: "taskCtrl",
inputs: {
title: "Add Task"
}
}).then(function (modal) {
//debugger;
modal.element.modal();
modal.close.then(function (result) {
});
});
};
Now the user keys in the Task details and Submits. The call is in my taskCtrl
The debugger does hit the code below and I can see the values submitted by the end user. The problem I am facing is that I am getting an error
at taskService.addTask invocation
The error is "Cannot read property 'addTask' of undefined"
fpdApp.kanbanBoardApp.controller('taskCtrl', function ($scope, taskService) {
$scope.close = function () {
debugger;
taskService.addTask($scope.Name, $scope.Desc, $scope.Estimate, 1).then(function (response) {
$scope.result = response.data;
}, onError);
close({
name: $scope.name,
Desc: $scope.Desc,
Estimate: $scope.Estimate,
}, 500); // close, but give 500ms for bootstrap to animate
};
});
Here is my taskService
fpdApp.kanbanBoardApp.service('taskService', function ($http, $q, $rootScope) {
var addTask = function (name, desc, estimate, projectId) {
debugger;
//return $http.get("/api/TaskWebApi/AddTaskForProject").then(function (response) {
// return response.data;
//}, function (error) {
// return $q.reject(error.Message);
//});
};
});
Can some one please help/ guide me whats wrong here.
Note that I have got other method calls working fine in the same service and controller.
Thanks in Advance
Venkat.

You need to expose addTask method in service. Right now it's just a local variable which cannot be accessed from outside. When the service is constructed it should create proper object with necessary methods. So you should set addTask either with this.addTask = addTask or by returning object with such method:
fpdApp.kanbanBoardApp.service('taskService', function ($http, $q, $rootScope) {
var addTask = function (name, desc, estimate, projectId) {
return $http.get("/api/TaskWebApi/AddTaskForProject").then(function (response) {
return response.data;
}, function (error) {
return $q.reject(error.Message);
});
};
return {
addTask: addTask
};
});

Service always returns a singleton object and that can be used by application wide.
You forget to write method inside service context,
change var addTask to this.addTask
Code
fpdApp.kanbanBoardApp.service('taskService', function($http, $q, $rootScope) {
this.addTask = function(name, desc, estimate, projectId) {
return $http.get("/api/TaskWebApi/AddTaskForProject").then(function(response) {
return response.data;
}, function(error) {
return $q.reject(error.Message);
});
};
});
Hope this could help you. Thanks.

Related

Googleapi - gapi not updating $scope object as expected in angularjs

I seem to get odd behavior from gapi.client.drive.files.list where I cannot update the scope from the promise it returns.
angular.module('myApp').controller("folder_controller", function($scope, $q, $http, $rootScope) {
$scope.list_subfolders = function () {
gapi.client.drive.files.list({
'q': "mimeType = 'application/vnd.google-apps.folder'",
'fields': "nextPageToken, files(id, name, parents, mimeType, description, starred, properties)"
}).then(function(response) {
$scope.subfolders = response.result.files;
console.log($scope.subfolders);
}, function(error){
console.log(error);
});
}
});
When I run list_subfolders()... the console.log displays $scope.subfolders fine... but the view never updates with that value - it is empty. I've tried various things including just assigning to $rootScope, but there is no way I can get the view to update with the $scope.subfolders.
Am I approaching this wrong? I can't understand why the variable is not updating.
Try this:
angular.module('myApp').controller("folder_controller", function($scope, $q, $http, $rootScope) {
$scope.list_subfolders = function () {
gapi.client.drive.files.list({
'q': "mimeType = 'application/vnd.google-apps.folder'",
'fields': "nextPageToken, files(id, name, parents, mimeType, description, starred, properties)"
}).then(function(response) {
$scope.subfolders = response.result.files;
// you need to refresh the view:
$scope.$apply();
console.log($scope.subfolders);
}, function(error){
console.log(error);
});
}
});

Angular $http issues and promises issues

I am Not able to pass Id in my modal which makes me impossible to pass data
Controller.js
app.controller('faq', function ($scope, faqservice, $ionicModal) {
$scope.faq = faqservice;
console.log($scope.faq); //upto this everything i working properly and i am able to render in my HTML page !
$ionicModal.fromTemplateUrl('templates/faqDetails.html', {
scope: $scope
}).then(function (modal) {
$scope.faqDetails = modal;
});
// Triggered in the FAQ detail modal to close it
$scope.faqClose = function () {
$scope.faqDetails.hide();
};
// Open the FAQ detail modal
$scope.faqOpen = function (id) {
$scope.faqDetails.show();
$scope.notes = faqservice.getid(id);
console.log($scope.notes); //**i am geting this null.. and when i console.log() in getID method in service my for loop is not executing **
};
});
Service.js
app.service("faqservice", function ($q, $http,Events,$ionicPopup) {
var self = {
'results': [],
getid: function (id) {
for (var i = 0; i < self.results.length; i++) {
if (self.results[i].id === parseInt(id)) {
return self.results[i];
}
}
return null;
},
'load': function () {
$http.get(Events.url +"/faqs")
.then(function (response) {
angular.forEach(response.data, function (data) {
self.results.push(data);
window.localStorage.setItem("faqs", JSON.stringify(data));
});
}
,function (data) {
$ionicPopup.alert({
title: 'Slow Internet connection',
template: 'Please check your internet connection for updates !'
});
if (window.localStorage.getItem("faqs") !== undefined) {
self.results.push(JSON.parse(window.localStorage.getItem("faqs")));
}
});
}
};
self.load();
return self;
});
*my error callback is not working when my internet connection is off! i am not getting error notifications whrn my internet connection is off *
I am Getting My $scope.notes null pls help me with this issue !!
and I am really new to Angular.js and ionic so can u pls suggest me what to
use success() or then() while working with HTTP ?
And what if You console.log(self.results.length) just before for loop ?
And i think success() method of $http is deprecated.

Getting Undefined in controller

I'm trying to get the value from service and then printing that value in console log which is giving me undefined in controller.
The value from service is being returned properly. But I'm not able to access vm.rrsData outside getRRSDetails function. vm.rrsData is comming as undefined outside the function.
Please suggest.
my controller :
(function () {
'use strict';
var angular = window.angular;
function RRSCtrl(
$translate,
RRSSvc
) {
var vm = this;
// Private
function getRRSDetails() {
RRSSvc.getRRSDetails()
.then(function (data) {
vm.rrsData = data;
});
}
getRRSDetails();
console.log('vm.rrsData'+ JSON.stringify(vm.rrsData)); // returning undefined here
}
angular
.module('quote')
.controller('RRSCtrl', [
'$translate',
'RRSSvc',
RRSCtrl
]);
}());
my service :
(function () {
'use strict';
var angular = window.angular;
function RRSSvc(
$http,
$q,
UserSvc,
UtilitiesSvc
) {
function rrsError(messageKey) {
UtilitiesSvc.showMessage(messageKey, 'error', 'generate-blank-demo-error');
}
function getRRSDetails(poID) {
return $http.get('quote/accounts/' + UserSvc.get('accountId') + '/pos/' + poID + '/rrs?serialNumber=')
.then(function (response) {
return response.data;
})
.catch(function (e) {
rrsError('quote.messages.GET_RRS_ERROR');
$q.reject(e);
});
}
return {
getRRSDetails: getRRSDetails
};
}
angular.module('quote')
.service('RRSSvc', [
'$http',
'$q',
'UserSvc',
'UtilitiesSvc',
RRSSvc
]);
}());
That's completely normal since you're making an asynchronous request.
consider these 2 lines:
getRRSDetails();
console.log('vm.rrsData'+ JSON.stringify(vm.rrsData)); // returning undefined here
console.log will run before the function above resolves. So, at that time vm.rrsData is undefined.
To see the value you must include console.log inside the function:
function getRRSDetails() {
RRSSvc.getRRSDetails()
.then(function (data) {
vm.rrsData = data;
console.log('vm.rrsData'+ JSON.stringify(vm.rrsData)); // has value from the http call
});
}
UPDATE
Another way to write the above and maybe more clear:
RRSSvc.getRRSDetails().then(onRSSDetails);
function onRSSDetails(response) {
// here you do whatever you want with data.
console.log(response);
}
Try to call your service in controller like this:
this.rrsData = null; //declare variavle to store service data
RRSSvc.getRRSDetails()
.then(function (data) {
this.rrsData = data;
}.bind(this)); // bind is the key to store the context
console.log('rrsData'+ JSON.stringify(this.rrsData));

proper use of error handling

I'm quite new to angularjs and I'm trying to figure out how to use a good and proper error handling when calling web api.
I have two methods which depends on each other, so I need to wait for the first method to finish before calling the second method. But if the web api returns internal server error (of something else), how should I take care of if in a proper way?
My firstMethod causes an error right now, but the $scope.scopeMethod is still keep on going. Should I use the error handling there instead?
angular.module("Module")
.controller("MyController",
function ($scope, $log, SecurityService) {
$scope.scopeMethod= function() {
SecurityService.firstMethod()
.then(function(firstResult) {
$scope.firstResult= firstResult;
SecurityService.secondMethod(firstResult)
.then(function (secondResult) {
$scope.secondResult= secondResult;
//Do stuff with secondresult
});
});
});
}
}
)
SecurityService:
angular.module('Security', []);
angular.module("Security")
.factory("SecurityService",
function($http, $cookies, $rootScope, $log) {
var service = {};
//firstMethod
service.firstMethod = function () {
return $http.get('/api/security/')
.then(function(result) {
return (result.data);
}, function(error) {
$log.error(error);
});
}
//secondMethod
service.secondMethod = function(username) {
return $http.get('/api/security/' + username)
.then(function(result) {
return (result.data);
});
}
return service;
}
);

Crud with angularjs and http service

I am starting to learn angularjs, so far i can create update delete withoud using services. I am trying to take it to the next level: Ive created a service page that looks like this:
app.factory('MainService', function($http) {
var getFeaturesFromServer = function() {
return $http.get('restfullfeatures/features');
}
var deleteFeature = function(id) {
return $http.post('restfullfeatures/delete', {'id': id});
}
var createFeature = function(feature) {
return $http.post('restfullfeatures/create', {'title': feature.title, 'description': feature.description});
}
return {
getHello : getHello,
getFeatures: getFeaturesFromServer,
deleteFeature: deleteFeature,
createFeature: createFeature
}
});
and my add function in controller looks like this:
$scope.add = function(){
MainService.createFeature($scope.formFeature)
.then(function(response) {
console.log('feature created',response.data);
$scope.features.push($scope.formFeature);
$scope.formFeature = {};
}, function(error) {
alert('error',error);
});
};
And this is my postCreate function:
public function postCreate()
{
\App\Feature::create(
['title' => \Input::get('title'),
'description' => \Input::get('description')
]);
return ['success' => true];
}
I have a table in my database called features, so basically what i am trying to do is add a new feature to my table using angularjs, my controller doesnt seem to recognize formFeature all i get is 'undefined' then i get the error: Cannot read property of type undefined, but I am using it in my delete function and it works perfectly, what did i miss here??
Factory
So when creating a factory for CRUD, try to lay out your factory like the example below. The example is some code I wrote for a project each call willl do a different thing, the idea is that you add a method that you can instantiate when you add the factory to your controller. (note: don't use $rootScope for session)
.factory('Chats', function ($http, $rootScope, $stateParams) {
return {
all: function () {
return $http.get('http://your_ip/chats', { params: { user_id: $rootScope.session } })
},
get: function () {
return $http.get('http://your_ip/chat', { params: { user_id: $rootScope.session, chat_id: $stateParams.idchat } })
},
add: function (id) {
return $http.post('http://your_ip/newChat', { params: {idfriends:id}})
}
};
});
Controller
when you instantiate this in your controller your looking at something like this
.controller('ChatsCtrl', function ($scope, Chats) {
Chats.all().success(function (response) {
$scope.chats = response;
});
$scope.getChat = function (id) {
Chats.get().success(function (response) { })
};
$scope.addChat = function (id) {
Chats.add(id).success(function (response) { })
};
})
$scope.remove and $scope.addChat and linked to buttons that will execute on click and $scope.chats is bound to the page via an ng-repeat.
Conclusion
Clean up your factories to look like this and you can easily write a series of reusable methods that are easy to instantiate in your controller.

Resources