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.
Related
i have service which makes an $HTTP.GET request, at first i tried to access the object $$state but the value inside was undefined, so i went and red about promises and asynchronous calls here:
http://blog.ninja-squad.com/2015/05/28/angularjs-promises/
after i red everything i tried again as guided but still it doesn't work for me :-(, please advise, i want to access the values object.
service:
function ConnectMe($http) {
function OnAction() {
this.create = function (search, key) {
return $http.get("https://www.tastekid.com/api/similar?q=" + search + "&verbose=1&k=" + key).then(function (response) {
return response.data;
});
};
}
var connection = new OnAction();
return function () {
return connection;
};
}
controller:
function TasteConroller($scope, ConnectMe) {
$scope.apiKey = "https://www.tastekid.com/api/similar?q=" + $scope.UserPick + "&verbose=1&k=254357-MatureAm-A31YEAIX";
$scope.UserPick = "red+hot+chili+peppers";
$scope.Key = "254357-MatureAm-A31YEAIX";
var srv = ConnectMe();
srv.create($scope.UserPick, $scope.Key).then(function(data) {
$scope.results = data;
}), function() {
$scope.error = 'unable to get the ponies';
};
console.log($scope.results);
Your service code looks a little suspect. I normally create a service like this;
function ServiceFunc( $http, $q ){
return {
OnAction: function( search, key ){
return $http.get(...)
.then( function( rsp ){ return rsp.data.foo })
.catch( function( err ){ $q.reject( err )})
}
}
I think you may have had a deeper level of functions whereby you weren't actually calling it.
I have an Angular controller and an Angular service. From my controller, I'm calling to the service.There are two functions in my Service. First function works fine. But this problem occurs with the second one. Following is the code for the relevant function.
function getCurrentUser() {
return $resource(_URLS.BASE_API + 'get_current_user' + _URLS.TOKEN_API + $localStorage.token).get().$promise;
}
Following the code for calling that service's function from the controller,
//Get current user id
$scope.getCurrentUserId = function() {
ParentService.getCurrentUser.then(function(response) {
if (response.query_status == "success") {
$scope.userid = response.data.id;
console.log('Value is: '+ $scope.userid);
} else {
$scope.userid = null;
}
}, function(error) {
$scope.userid = null;
console.log("Error : Failed to load user data...");
console.log(error);
});
};
I can't figure out what the issue is since my first function works fine. So hope someone will help me to solve this issue.
Your controller code should be as following. Notice the () in ParentService.getCurrentUser()
$scope.getCurrentUserId = function() {
ParentService.getCurrentUser() // notice the "()" here
.then(function(response) {
...
}, function(error) {
...
});
};
I have the following controller:
.controller('GitCtrl', function ($scope, $http, Chats) {
$scope.search = function () {
$id = 1;
$scope.repos = Chats.all($http);
$scope.repos2 = Chats.get($id);
}
})
The only thing which does not work when I click a button which invokes the search function is Chats.all, which comes from the following service (along with Chats.get):
.factory('Chats', function ($http) {
var chats = [{
id: 0,
name: 'Ben Sparrow',
lastText: 'You on your way?',
face: 'img/ben.png'
}, {
id: 1,
name: 'Max Lynx',
lastText: 'Hey, it\'s me',
face: 'img/max.png'
}];
return {
all: function () {
var user = $('#gitdata-input').val();
$http.get("https://api.github.com/users/" + user + '/repos').then(function (resp) {
console.log('Success', resp);
var repos = resp.data;
return repos;
}, function (err) {
console.error('ERR', err);
})
},
get: function(chatId) {
for (var i = 0; i < chats.length; i++) {
if (chats[i].id === parseInt(chatId)) {
return chats[i];
}
}
return null;
}
};
});
Chats.get and the chats array are merely for testing purposes.
I have verified that the service works, as I 'Succes' gets logged to my console and I also see that ver repos contains my data. In the controller however,$scope.repos stays undefined. $scope.repos2 does work. Then I noticed in the console that the Chats.all function from the service (in which I have a breakpoint) gets called AFTER $scope.repos2 is already filled with the result of Chats.get. So why is this? And is it also what is causing me to not receive the data from Chats.All in my controller?
while Chats.get() and Chats.remove() are synchronous, the function Chats.all() is asynchronous since it contains an http call, hence when you do:
$scope.repos = Chats.all($http);
You are basically returning undefined.
I would suggest you to use promises, hence changing your Chats.all() code to this:
all: function () {
return $q(function(resolve,reject) {
var user = $('#gitdata-input').val();
$http.get("https://api.github.com/users/" + user + '/repos').then(function (resp) {
console.log('Success', resp);
resolve(resp.data);
}, function (err) {
reject(err);
});
}
},
And the line in the controller as following:
Chats.all($http).then(function(data) {$scope.repos = data;});
Cheers!
The accepted answer is bad practice and should be avoided when possible.
An angular $http call is returning a promise and should not be wrapped in another promise ($q). It would suffice to return the promise of the $http call itself.
In short:
app.factory('Chats', function($http) {
return {
all: function(user) {
return $http.get("https://api.github.com/users/" + user + "/repos")
.then(function(resp) {
return resp.data;
}, function(err) {
console.log('ERR', err);
});
}
};
});
should do the trick. (See plunker) and surely do read why wrapping promises in promises should be avoided here.
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.
I have written a service, depending on an other service. But initialisation is not working.
You can find a plunker as showcase
Should be close to working... Any tipps?
Thanks in advance!
edit: The plunker is fixed now and can be used as reference.
You need to either change your testServiceMockConfig and testService from factory to service, for example:
.service('testServiceMockConfig', function ()
or keep them as factories and add return.this; at the bottom of both of them or restructure them like this (recommended):
angular.module('testServiceMockConfig', [])
.factory('testServiceMockConfig', function() {
console.log("setup cqrs mock config.");
return {
doLoadItems: function(callback) {
console.log("mock loading data");
if (!this.configuredLoadItems) {
throw Error("The mock is not configured to loadItems().");
}
callback(this.loadItemsError, this.loadItemsSuccess);
},
whenLoadItems: function(success, error) {
this.configuredLoadItems = true;
this.loadItemsSuccess = success;
this.loadItemsError = error;
}
};
});
I also assume that loadItems in testService should call:
testServiceMockConfig.doLoadItems(callback);
instead of:
testService.doLoadItems(callback);
As I see from your example,
you didn't define properly the factory. The this key used for service
in testService.doLoadItems(callback); replace with testServiceMockConfig.doLoadItems(callback);
The difference between service - factory - provider and definition you can find in this simple demo:
Fiddle
Fixed example:
angular.module('testServiceMockConfig', [])
.factory('testServiceMockConfig', function () {
console.log("setup cqrs mock config.");
return{
doLoadItems : function (callback) {
console.log("mock loading data");
if (!this.configuredLoadItems) {
throw Error("The mock is not configured to loadItems().");
}
callback(this.loadItemsError, this.loadItemsSuccess);
},
whenLoadItems : function (success, error) {
this.configuredLoadItems = true;
this.loadItemsSuccess = success;
this.loadItemsError = error;
}
}
});
angular.module('testService', ['testServiceMockConfig'])
.factory('testService', ['testServiceMockConfig', function (testServiceMockConfig) {
console.log("mock version. testServiceMockConfig: ");
return {
loadItems : function (callback) {
testServiceMockConfig.doLoadItems(callback);
}
}
}])
angular.module('ItemApp', ['testService'])
.controller('ItemsCtrl', ['$scope', 'testService', function ($scope, testService) {
$scope.text = 'No items loaded';
testService.loadItems(function (error, items) {
if (error) {
$scope.text = "Error happened";
}
$scope.text = '';
for (i = 0; i < items.length; i++) {
$scope.text = $scope.text + items[i].name;
}
})
}]);
Demo Plunker