I'm trying to write down a Controller that pass a var to a Factory in Angularjs.. The following code return (in console) the values, but I'm not been able to load that into my html page.
Just to record, yes, I'm starting in angularjs.
app.js
var myApp = angular.module('myApp',[]);
myApp.factory('eventData', function ($http, $q) {
delete $http.defaults.headers.common['X-Requested-With'];
return {
getEvent: function (id) {
var deferred = $q.defer();
$http({
method: 'GET',
url: 'page' + id
}).
success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
myApp.controller('AngularJSCtrl',
function FeederController($scope, eventData) {
$scope.data = [];
for (var i = 0; i < 10; i++) {
eventData.getEvent(i).then(
function (data) {
$scope.data = data;
console.log($scope.data);
},
function (statusCode) {
console.log(statusCode)
});
}
}
);
page.html
<div ng-controller="AngularJSCtrl">
<div ng-repeat="patient in patients">
<businesscard>{{patient.name}}</businesscard>
</div>
</div>
Problem solved. I've searched for a while until get this right.
Thanks for #Claies and Brad Barrow for the tips :)
app.js
var myApp = angular.module('myApp',[]);
myApp.factory('patientsData', function ($http) {
delete $http.defaults.headers.common['X-Requested-With'];
return {
getPatients: function () {
return $http({
url: 'http://localhost/ucamradio/php/tst.php?campusId=1',
method: 'GET'
})
}
}
});
myApp.controller('AngularJSCtrl', function($scope, patientsData){
$scope.patients = [];
var handleSuccess = function(data, status) {
//$scope.patients = data;
$scope.patients.push(data);
console.log($scope.patients);
};
patientsData.getPatients().success(handleSuccess);
});
page.html
<div ng-controller="AngularJSCtrl">
<div ng-repeat="patient in patients">
<businesscard>{{patient.name}}</businesscard>
</div>
<!--
<div ng-repeat="patient in patients ">
<businesscard>{{patient.id}}</businesscard>
</div> -->
</div>
Related
Although there are many questions regarding the subject , yet I am unable to figure it out , how to proceed further.
I am new in AngularJS. I want to pass data coming from API in Controller and pass it to another function. For this I know I have to create a Service. But after coming to this extend of code I am unable to figure it, how to store it in Service and pass it on other Controller or of function within same Controller. I am new in making Service.
Controller:
$scope.GetR = function (){
$scope.X = null;
$scope.Y = null;
$http({method: 'POST', url: 'http://44.43.3.3/api/infotwo',
headers: {"Content-Type": "application/json"},
data: $scope.ResponseJson
})
.success(function(data, status, headers, config) {
$scope.X = data.X;
$scope.Y = data.Y;
//console.log($scope.X+"and"+$scope.Y);
//Seding RS to API to get AAs
$scope.RJson = {
"ICl": $scope.ICl,
"RS": $scope.X
};
$http({method: 'POST', url: 'http://44.128.44.5/api/apithree',
headers: {"Content-Type": "application/json"},
data: $scope.RJson
})
.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:"+$scope.Eq+" FIn:"+$scope.FIn+" MM:"+$scope.MM);
}).error(function(data, status, headers, config) {
console.log("API failed...");
});
}).error(function(data, status, headers, config) {
console.log("Something went wrong...");
});
};
Now I want to pass this data to Service so that I can call this output on other API input
.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:"+$scope.Eq+" FIn:"+$scope.FIn+" MM:"+$scope.MM);
This shows how to create a service and share data between two controllers.
The service:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.service('MyService', MyService);
MyService.$inject = [];
function MyService() {
this.data = null;
}
})();
First controller:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.controller('MyFirstController', MyFirstController);
MyFirstController.$inject = ['MyService', '$http'];
function MyFirstController(MyService, $http) {
var vm = this;
vm.data = MyService.data;
$http.post('/someUrl', whatEverData).then(resp=> {
MyService.data = resp.data;
})
}
})();
Second controller:
(function() {
'use strict';
angular
.module('myAppName') // Replace this to your module name
.controller('MySecondController', MySecondController);
MySecondController.$inject = ['MyService', '$http'];
function MySecondController(MyService, $http) {
var vm = this;
vm.data = MyService.data; // Here you can use the same data
}
})();
Not sure if this is what you are looking for. Below code is not tested (May have syntax errors)
Service:
function() {
'use strict';
angular
.module('myAppName')
.factory('MyService', MyService);
MyService.$inject = [];
function MyService() {
var data = null;
return {
getData: function() {
return data;
},
setData: function(d) {
data = d;
}
}
}
})();
Controller:
(function() {
'use strict';
angular
.module('myAppName')
.factory('controller', controller);
controller.$inject = ['$scope', '$http', 'MyService'];
function controller($scope, $http, MyService) {
$scope.GetR = function() {
$scope.X = null;
$scope.Y = null;
var promise = $http({
method: 'POST',
url: 'http://44.43.3.3/api/infotwo',
headers: {
"Content-Type": "application/json"
},
data: $scope.ResponseJson
});
promise.success(function(data, status, headers, config) {
$scope.X = data.X;
$scope.Y = data.Y;
//console.log($scope.X+"and"+$scope.Y);
//Seding RS to API to get AAs
$scope.RJson = {
"ICl": $scope.ICl,
"RS": $scope.X
};
}).error(function(data, status, headers, config) {
console.log("Something went wrong...");
});
return promise;
};
$scope.sendRS = function() {
var promise = $http({
method: 'POST',
url: 'http://44.128.44.5/api/apithree',
headers: {
"Content-Type": "application/json"
},
data: $scope.RJson
});
promise.success(function(data, status, headers, config) {
$scope.At = data;
$scope.Eq = data.AA.Eq;
$scope.FIn = data.AA.FIn;
$scope.MM = data.AA.MM;
console.log("Eq:" + $scope.Eq + " FIn:" + $scope.FIn + " MM:" + $scope.MM);
}).error(function(data, status, headers, config) {
console.log("API failed...");
});
return promise;
}
var init = function() {
$scope.GetR().then(function() {
$scope.sendRS().then(function(data) {
MyService.setData({
At: data,
Eq: data.AA.Eq,
FIn: data.AA.FIn,
MM: data.AA.MM
});
})
})
}
init();
}
})();
Other controller
(function() {
'use strict';
angular
.module('myAppName')
.controller('controller1', controller1);
controller1.$inject = ['$scope', 'MyService'];
function controller1($scope, MyService) {
$scope.data = MyService.getData();
}
})();
books.html
<div ng-controller="BookController">
<table datatable="ng" class="row-border hover" ng-table="tableParams">
<thead>
<tr>
<th>BookID</th>
<th>BookName</th>
<th>Author</th>
<th>ISBNCode</th>
<th>NoOfBooks</th>
<th>PublishDate</th>
<th>NoOfBooksIssued</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="book in books">
<td>{{book.BookId}}</td>
<td>{{book.BookName}}</td>
<td>{{book.Author}}</td>
<td>{{book.ISBNCode}}</td>
<td>{{book.NoOfBooks}}</td>
<td>{{book.PublishDate}}</td>
<td>{{book.NoOfBooksIssued}}</td>
<td><p data-placement="top" data-toggle="tooltip" title="Edit"><button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit"><span class="glyphicon glyphicon-pencil"></span></button></p></td>
<td><p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-xs" data-title="Delete" data-toggle="modal" data-target="#delete"><span class="glyphicon glyphicon-trash"></span></button></p></td>
</tr>
</table>
</div>
Bookcontroller.js
"use strict";
(function () {
angular.module("Bookapp")
.controller("BookController", ["$scope", "BookService",
function ($scope, bookService) {
bookService.getRequest()
.then(function (response) {
$scope.books = JSON.parse(response);
});
}]);
})();
AddBookController.js
"use strict";
(function () {
angular.module('Bookapp')
.controller('AddBookController', ["$scope", "BookService",
function ($scope, bookService) {
$scope.save = function (item) {
bookService.postRequest(item)
.then(function () {
location.path("books");
});
}
}]);
})();
Both the js files are 2 different custom files which are included in the master page. I have also written BookService.js. Which is as follows:
"use strict";
(function () {
angular.module("Bookapp")
.factory("BookService", ["$http", "$q", function ($http, $q) {
var baseURL = "http://localhost:27136/api/book";
var getRequest = function (query) {
var deferred = $q.defer();
$http({
url: baseURL,
method: "GET"
})
.success(function (result) {
deferred.resolve(result);
})
.error(function (result, status) {
deferred.reject(status);
});
return deferred.promise;
};
var getByIdRequest = function (id) {
var deferred = $q.defer();
$http({
url: baseURL + "/" + id,
method: "GET"
})
.success(function (result) {
deferred.resolve(result);
})
.error(function (result, status) {
deferred.reject(status);
});
return deferred.promise;
};
var postRequest = function (data) {
var deferred = $q.defer();
$http({
url: baseURL,
method: "POST",
data: JSON.stringify(data)
})
.success(function (result) {
deferred.resolve(result);
})
.error(function (result, status) {
deferred.reject(status);
});
return deferred.promise;
};
var updateRequest = function (data, id) {
var deferred = $q.defer();
$http({
url: baseURL + "/" + id,
method: "PUT",
data: JSON.stringify(data)
})
.success(function (result) {
deferred.resolve(result);
})
.error(function (result, status) {
deferred.reject(status);
});
return deferred.promise;
};
var deleteRequest = function (id) {
var deferred = $q.defer();
$http({
url: baseURL + "/" + id,
method: "DELETE"
})
.success(function (result) {
deferred.resolve(result);
})
.error(function (result, status) {
deferred.reject(status);
});
return deferred.promise;
};
return {
getRequest: getRequest,
getByIdRequest: getByIdRequest,
postRequest: postRequest,
updateRequest: updateRequest,
deleteRequest: deleteRequest
};
}]);
})()
My problem is when I click on the add button below my table the details of the book that i have entered must update in the table immediately which is not happening in my case. I have 2 different controllers one is BookController which will get all the books details from db using a service method and display in the table. The other one is AddBookController which will add the new book details to the table.In AddBookController itself i have written code to get the data after posting it to db. But i am not able to refresh the table with new data.Please help me. Thank you so Much in advance!
First of all you have a code smell in your service because you don't need to use $q service for retrieving a promise from $http.
$http always return a promise itself!
so you can simplify all your functions like this:
var getRequest = function (query) {
return $http({
url: baseURL,
method: "GET"
});
};
For your question
Have you try debugging the bookService.getRequest() request?
Try putting a console.log in your book controller and see if it's called after the add.
Maybe you need to trigger the get request after the add.
"use strict";
(function () {
angular.module('Bookapp')
.controller('AddBookController', ["$scope", "BookService",
function ($scope, bookService) {
$scope.save = function (item) {
console.log(item);
bookService.postRequest(item)
.then(function () {
bookService.getRequest()
.then(function (response) {
$scope.books = JSON.parse(response);
});
});
}
}]);
})();
Im a complete angularjs newbie. So hopefully I am somewhat on track.
I have a datacontext configured like
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('app').factory(serviceId, ['common', '$http', datacontext]);
function datacontext(common, $http) {
var $q = common.$q;
var service = {
getCustomerGroups: getCustomerGroups
};
return service;
function getCustomerGroups() {
var groups = [];
$http({ method: 'GET', url: '/api/getgroups' }).
success(function (data, status, headers, config) {
console.log(status);
console.log(headers);
console.log(data);
groups = data;
return $q.when(groups);
}).
error(function (data, status, headers, config) {
console.log(data);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
return $q.when(groups);
}
}
})();
Within my view I am using ngTagsInput
<tags-input ng-model="groups"
display-property="GroupName"
placeholder="Add Customer Group"
enableeditinglasttag="false"
class="ui-tags-input"
replace-spaces-with-dashes="false">
</tags-input>
And finally my controller
(function () {
'use strict';
var controllerId = 'customers';
angular.module('app').controller(controllerId, ['common','$scope','$http','datacontext', customers]);
function customers(common,$scope,$http,datacontext) {
var vm = this;
vm.title = 'Customers';
$scope.groups = [];
function getGroups() {
return datacontext.getCustomerGroups().then(function (data) {
return $scope.groups = data;
});
}
activate();
function activate() {
var promises = [getGroups()];
common.activateController(promises, controllerId)
.then(function() {
}
);
}
}
})();
I am not getting any errors and I can see the correct data is returned in the success method of $http. However the tag is not populated. Is it because the tag is calling the datasource before the $http has completed?
I am not sure how $q.when works, but it returns promise but does not resolve it. You should us the defer api.
So at start set
var defer = common.$q.defer();
and later in success do defer.resolve.
success(function (data, status, headers, config) {
console.log(status);
console.log(headers);
console.log(data);
groups = data;
defer.resolve(data);
and see if it works.
I have a service that looks like:
myApp.service('peerService', [
'$http', function($http) {
this.getPeers = function() {
return $http({
url: '/api/v1/peers',
method: 'GET'
});
};
}
]);
In my controller, I have:
myApp.controller('PeerComparisonController', [
'$scope', '$rootScope', 'peerService', function($scope, $rootScope, peerService) {
$scope.init = function() {
$rootScope.pageTitle = 'Peer Comparison';
return $scope.peers = [];
};
$scope.getPeers = function() {
return peerService.getPeers().then(function(response) {
console.log(response);
return $scope.peers = response.data;
});
};
return $scope.init();
}
]);
My view has {{ peers }} in it. This does not get updated when the service returns. I've tried:
peerService.getPeers().then(function(response) {
return $scope.$apply(function() {
return $scope.peers = response.data;
});
});
And that also doesn't work. So any ideas?
you try something like this
myApp.service('peerService', [
'$http', function($http) {
this.getPeers = function() {
return $http({method: 'GET', url:'/api/v1/peers'}).
then(function(response) {
return response.data;
});
};
}
]);
or
myApp.service('peerService', ['$http', function ($http) {
this.getPeers = function () {
var deferred = $q.defer();
$http({ method: 'GET', url: '/api/v1/peers' }).
then(function (response) {
deferred.resolve(response.data);
});
return deferred.promise;
};
}
]);
In my angularjs code below why is the IsLoggedIn and Username not available to the view. Not sure what's wrong, any help will be highly appreciated:
'use strict';
myApp.controller('masterPageController',
function masterPageController($scope, loginService, stateService) {
$scope.State = stateService.State;
});
myApp.factory('stateService', function () {
// todo: fetch the state from server when the service is initialised
var state = {};
return {
State: state,
};
});
myApp.factory('loginService', function ($http, $q, stateService) {
return {
Login: function (logindetails) {
var deferred = $q.defer();
$http({ method: 'POST', url: '/api/Login/Login', data: JSON.stringify(logindetails), headers: { 'Content-Type': 'application/json' } }).
success(function (data, status, headers, config) {
stateService.State = data.State;
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
<div ng-controller="masterPageController">
<div>
<div>
<div>
<a href="/logout" ng-show="State.IsLoggedIn" >{{ State.Username }}</a>
</div>
</div>
</div>
</div>
EDIT: It doesn't work when I set the stateService.State property in my loginService
Change the way you build the service from "factory" to "service" and define "state" on this and do not return anything.
myApp.service('stateService', function () {
// todo: fetch the state from server when the service is initialised
this.state = {};
});
http://codepen.io/rotempe4/pen/KNMpzZ