AngularJs call controller function from factory - javascript

I'm trying a sample with angularJs where I'm trying to call a factory method and in the factory method, I'm doing an ajax callback to get result from database and in the success event of the ajax callback, I need to call a function in the controller to bind the result to the UI.
My Angular Code:
angular.module('myApp.controllers', [])
.controller('TasksListCtrl', ['$scope', '$rootScope', '$routeParams', 'Task',
function($scope, $rootScope, $routeParams, Task) {
debugger;
//factory call
Task.query({
MobileNumber: $routeParams.MobileNumber,
ClientCode: $routeParams.ClientCode
});
$rootScope.UserMobileNumber = $routeParams.MobileNumber;
$scope.BindTasksList = function(resultData) {
debugger;
$scope.Tasks = resultData;
$scope.$apply();
}
}
]);
My Angular Factory Code:
'use strict';
(function() {
function GetTasks(MobileNumber, ClientCode) {
debugger;
$.ajax({
url: '/api/TasksAPI/GetTasksList',
type: 'GET',
datatype: 'json',
data: {
'MobileNumber': MobileNumber,
'ClientCode': ClientCode
},
success: function(response) {
debugger;
$scope.BindTasksList(response);
},
error: function(xhr) {}
});
};
angular.module('myApp.DbScripts', [])
.factory('Task', [
function() {
return {
query: function(data) {
debugger;
GetTasks(data.MobileNumber, data.ClientCode);
}
}
}
]);
}());
My app.js Code:
'use strict';
angular.module('myApp', [
'ngTouch',
'ngRoute',
'ngAnimate',
'myApp.controllers',
'myApp.DbScripts'
]).
config(['$routeProvider',
function($routeProvider) {
debugger;
$routeProvider.when('/tasks/:MobileNumber/:ClientCode', {
templateUrl: 'partials/tasks-list.html',
controller: 'TasksListCtrl'
});
$routeProvider.when('/tasks/:taskId', {
templateUrl: 'partials/task-details.html',
controller: 'TaskDetailCtrl'
});
$routeProvider.when('/tasks/:taskId/status', {
templateUrl: 'partials/task-completion-details.html',
controller: 'TaskCompletionDetailCtrl'
});
$routeProvider.when('/tasks/:taskId/route', {
templateUrl: 'partials/route-details.html',
controller: 'RouteDetailCtrl'
});
$routeProvider.otherwise({
redirectTo: '/tasks'
});
}
]);
But, I'm unable to call the function in controller. I've also tried it with angular.element(document.getElementById('TasksListCtrl')).scope().BindTasksList(response). But even that's not working.
Can anyone please point out the mistake I'm doing?
How to send the $scope of the controller to the factory?

You can do this by leveraging the $http promises, in you factory, return the promise instead as follows
'use strict';
(function() {
function GetTasks(MobileNumber, ClientCode) {
};
angular.module('myApp.DbScripts', [])
.factory('Task', [
function($http) {
return {
query: function(data) {
return $http({
url: '/api/TasksAPI/GetTasksList',
method: 'GET',
params: {
'MobileNumber': data.MobileNumber,
'ClientCode': data.ClientCode
}
}).then(function(result) {
return result;
});
}
}
}
]);
}());
Then in your controller you can access the $http response object that is returned:
//factory call
Task.query({
MobileNumber: $routeParams.MobileNumber,
ClientCode: $routeParams.ClientCode
}).then(function(resp) {
// access $http resp here and attach to $scope.Tasks
});
If you can, I would advocate using $q along $http as well, so that you do not need to parse through the http response and get a nice little response data object back
plnk

Related

AngularJS ui router (resolve part)

I wrote ui.router to get data from JSON file.
I am not getting error messages, but code does not enter "resolve" part.
So I cannot get data from JSON file.
Can anyone tell me what could possibly make this happen and the way to fix it?
Here is my code.
(function(){
/*
* Declaration of main angular module for this application.
*
* It is named turtleFacts and has no dependencies (hence the
* empty array as the second argument)
*/
angular
.module('GrammarQuiz', ['ui.router'])
.config(
function($stateProvider, $urlRouterProvider) {
console.log('HOLY SMOKES, I CAN BREATHE IN HERE')
$urlRouterProvider.otherwise('/browse/1');
$stateProvider
.state('home',{
url: "/#/testtest",
resolve: {
questions: function($http){
console.log('!!##!##!');
return $http({
method: 'GET',
url: 'api/data1.json'
}).error(function(data,status,headers,config){
console.log('thisi now working!!!!');
})
}
}
})
})
})();
I'm pretty sure you have to return the value you want from the $http callbacks:
resolve: {
questions: function($http) {
return $http({
method: 'GET',
url: 'api/data1.json'
}).success(function(data) {
return data; // this is what you're missing
}).error(function() {
console.log('error');
});
}
}
But you should really use .then instead of .success and .error
resolve: {
questions: function($http) {
return $http({
method: 'GET',
url: 'api/data1.json'
}).then(function success(response) {
return response.data;
}, function error(response) {
console.log('error');
});
}
}
try to change question: function ($http)... to
question: ['$http', fucntion($http) {..}]

Populate a table dynamically in Angular

I am new to Angular. I have created an app that, given the click of a button, should trigger a call that gets a set of json objects and populate a specific table. In the following controller code I have managed to populate the table directly without the click of a button (via the this.tableParams), but what I want is to trigger this data fetching process and populate the table only when the populateTable() function is called.How do I do it?
(function() {
'use strict';
angular
.module('anomalies')
.controller('controller', ['$log', '$scope', '$http', 'NgTableParams', function ($log, $scope, $http, NgTableParams) {
$scope.populateTable = function () {
//
}
this.tableParams = new NgTableParams({}, {
filterDelay: 300,
getData: function (params) {
return $http({
method: 'GET',
url: '/server/data.json'
}).then(function (response) {
return response.data;
}, function (response) {
$log.log(response);
return [];
});
}
});
}]);
})();
Why not creating the NgTableParams-object inside the populateTable-function?
angular
.module('anomalies')
.controller('controller', ['$log', '$scope', '$http', 'NgTableParams', function ($log, $scope, $http, NgTableParams) {
$scope.populateTable = function () {
this.tableParams = new NgTableParams({}, {
filterDelay: 300,
getData: function (params) {
return $http({
method: 'GET',
url: '/server/data.json'
}).then(function (response) {
return response.data;
}, function (response) {
$log.log(response);
return [];
});
}
});
}.bind(this);
}]);
Not the .bind(this). This ensures the this keyword means the same inside the populateTable-function as in the controller.
Move this.tableParams into the $scope.populateTable function. Bind this function to a button in the view e.g <button ng-click="populateTable()">Click Me!</button>

Angularjs Ajax get sending headers

I'm new to angularjs, and im using a service for my http requests.
one of the rest api's i need to send key value pairs in the header.
username: foo
password: bar
how do i do it using the http request format i have in my service. (i'm aware i need to pass an argument in the function i don't how to go about it and what object format)
.service('UserService', ['$http', '$rootScope', function ($http, $rootScope) {
this.CheckIfUserExists = function () {
return $http.get($rootScope.endPoint + '/user/email_token');
};
}
...
//in the controller
UserService.CheckIfUserExist()
.success(function (data) {
console.log(data);
//handler
}).
error(function(error) {
//handler
});
Example from the doc
you need know what kind of auth. you can use post for example.
.service('UserService', ['$http', '$rootScope', function ($http, $rootScope) {
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).success(function(){...}).error(function(){...});
In your case:
.service('UserService', ['$http', '$rootScope', function ($http, $rootScope) {
this.CheckIfUserExists = function () {
var req = {
method: 'POST',
url: 'http://example.com'
data: { 'username': 'foo', 'password': 'bar' }
};
return $http(req);
}
}

angularjs getting data from a url

I want to get json data from the url and assign it to a variable. I use a service that looks like this
app.service('dataService', function($http) {
this.getdata = function(callbackFunc) {
$http({
method: 'GET',
url: '/records/json/',
}).success(function(data){
// With the data succesfully returned, call our callback
callbackFunc(data);
}).error(function(){
alert("error");
});
}
});
and my controller looks like this
app.controller('ReCtrl', ['$scope', function($scope, dataService){
dataService.getdata(function(dataResponse) {
$scope.fields = dataResponse;
});
....
But I get error TypeError: Cannot read property 'getdata' of undefined. I dont know what i am doing wrong. I appreciate any help.
You are not injecting your service (dataService) into your controller:
app.controller('ReCtrl',
['$scope', 'dataService', function($scope, dataService){
dataService.getdata(function(dataResponse) {
$scope.fields = dataResponse;
});
....
Note the extra string 'dataService' after '$scope' while defining the controller ReCtrl.

ng-click change route in angularjs with param

I would like to change the route of an angularjs application build with ionic framework, but the route didn't change
this is my code of app.js
angular.module('starter', ['ionic', 'starter.controllers'])
.state('app.annuaire.menuitempage', {
url: "/menuitempage/:ID",
views: {
'menuContent' :{
templateUrl: "templates/menuItemPage.html",
controller: function($stateParams){
$stateParams.ID ;
}
}
}
})
.state('app.annuaire', {
url: "/annuaire",
views: {
'menuContent' :{
templateUrl: "templates/annuaire.html",
controller: 'MenuItemCtrl'
}
}
})
And this is the code of my controller
angular.module('starter.controllers', [])
.controller('MenuItemCtrl', function($scope, $http, $location) {
$scope.itemsMenu = {};
var responsePromise = $http.get("http://monguidepratique.com/mobile/getCategories.php?parent_id=0");
responsePromise.success(function(data, status, headers, config) {
//alert(data);
$scope.itemsMenu = data;
});
responsePromise.error(function(data, status, headers, config) {
alert("AJAX failed!");
});
$scope.itemClick = function(path){
alert(1);
$location.path(path);
};
})
And this is my html code in annuaire.html
<div class="col" ng-click="itemClick('/menuitempage/1628')"><img class="img_menu" src="img/home.png"><p class="titre_center">Accueil</p></div>
Try
$location.path(path)
instead of
$state.go(path)
You need to inject $location service into your controller.
Edit
If you are using $state.go - you should to use it next way:
$scope.itemClick = function(id){
$state.go('app.annuaire.menuitempage', {'ID': id})
};
And HTML:
<div class="col" ng-click="itemClick(1628)"><img class="img_menu" src="img/home.png"><p class="titre_center">Accueil</p></div>
The first param is state name, not URL, the second is an Object with your params.
I solved my problem
in annuaire.html i changed
itemClick('/menuitempage/1628')
by
itemClick('/app/menuitempage/1628')
and i changed the route name app.annuaire.menuitempage by
app.menuitempage
.state('app.menuitempage', {
url: "/menuitempage/:ID",
views: {
'menuContent' :{
templateUrl: "templates/menuitempage.html",
controller: 'SubMenuCtrl'
}
}
})

Categories

Resources