Change Http.get Url and show again in ng-repeat - angularjs

I have url that returns data
I read data with angular
var appModule;
(function () {
appModule = angular.module('Ryka', []);
appModule.controller('TaskControler', ['$scope', '$http', function (scope, http) {
scope.mytask = mytask;
http.get('http://localhost/_vti_bin/RykaSolution/RykaService.svc/MyOverDueTasks/first').success(function (data) {
scope.Tasks = data}).error(function (err) { alert(err) })
}]);
})();
i want to change http.get url using ng-click ... this code executes when the page loads

You could do it like this (simplified example):
(function () {
var appModule = angular.module('Ryka', []);
appModule.controller('TaskControler', ['$scope', '$http', function (scope, http) {
scope.tasks = undefined;
$scope.getTasks = function (type) {
http.get('http://localhost/tasks/' + type).success(function (data) {
scope.tasks = data
}).error(function (err) {
// Handle error
})
}
// Initial loading of data.
$scope.getTasks("overdue");
}]);
})();
Just a little bit of explanation. Calling $scope.getTasks("overdue") would result in the URL like this:
http://localhost/tasks/overdue
You could then call the same method from your view like this:
<a ng-click="getTasks('current')">Get my current tasks</a>
which would result in a such URL:
http://localhost/tasks/current
I hope you got and idea.
PS: You would be better off by moving getTask method into a service.

Related

Angular JS 1.6 help as a Service results in an UNK Provider when what I'm doing is perfectly correct

So, I am doing VERY SIMPLE controller like I've done before on my personal website I made back 8 years ago.
What I'm facing is an enormous app with code that followed no coding standards.
Here's my controller, inside a controller.js file:
app.controller("documentController", ["$scope", "documentService", ($scope, documentService) => {
let docCtrl = $scope;
//docCtrl = 'Hello World!';
docCtrl.docContent = [];
console.log('DOC CONTROL: ', docCtrl.content);
docCtrl.fetchDocs = function () {
documentService.getDocuments().then(function (result) {
docCtrl.docContent = result.data;
console.log('DOCS RETRIEVED: ', docCtrl.docContent);
});
}
docCtrl.fetchDocs();
}]);
and the service I need call inside a service.js file that's in the same module folder.
app.service('documentService', ["$http", "URL", ($http, URL) => {
let getDocuments = function () {
return $http.get(URL)
.success(function (data) {
console.log('SUCCESS: Documents retreived', data);
return data;
})
.error(function (e) {
console.log(`He's dead Jim!`, e);
return e;
})
}
return ({
getDocunment: getDocuments
});
}]);
Inside that controller.js file is a 2584 line controller set up the same way as my very simple controller that calls an 1000 line service in the service.js file.
My code sits at the bottom.
What happens is, when I run the app, I get UNK Provider error for the service.
Oh, I have a directive that also sits in the controller.js which is found and works.
app.directive("documentDirective", ["$compile", ($compile) => {
let data = {};
data.restrict = 'AE';
data.link = async ($scope, $element) => {
const template = '<span>Hello World!</span>'
await $element.html('').append($compile(template)($scope));
};
return data;
}]);
So, when I take out the call to the service, which I need, I get no errors.
When I put the service in the app.controller() that already exists in the controller.js file and call it, I still get UNK Provider. This makes ABSOLUTELY no sense.
[$injector:unpr] http://errors.angularjs.org/1.5.7/$injector/unpr?p0=URLProvider%20%3C-%20URL%20%3C-%20documentService
My personal website: www.peterborreggine.us, if you open the debug console and view: the Angular folder --> Controllers and Services, you'll see how I'm doing exactly what I am trying to accomplish here.
Of note, there are 65 module folders in the module directory all with their own controller.js and service.js. But only one controller and one service per file is there.
Again, I've been using Angular since its inception and now on Angular 12. This telecom company needs to upgrade to at least Angular 12
UPDATE:
I just tried this with the same UNK Provider error and this is suggested in Angular's error above! I combined both the service and controller and STILL the same error
// Combined Service and then my Controller
app.service('documentService', ["$http", "URL", ($http, URL) => {
let getDocuments = function () {
return $http.get(URL)
.success(function (data) {
console.log('SUCCESS: Documents retreived', data);
return data;
})
.error(function (e) {
console.log(`He's dead Jim!`, e);
return e;
})
}
return ({
getDocunment: getDocuments
});
}]).controller("documentController", ["$scope", "documentService", ($scope, documentService) => {
let docCtrl = $scope;
//docCtrl = 'Hello World!';
docCtrl.docContent = [];
console.log('DOC CONTROL: ', docCtrl.content);
docCtrl.fetchDocs = function () {
documentService.getDocuments().then(function (result) {
docCtrl.docContent = result.data;
console.log('DOCS RETRIEVED: ', docCtrl.docContent);
});
}
docCtrl.fetchDocs();
}]);

pass data between controllers in AngularJS dynamically [duplicate]

This question already has answers here:
Share data between AngularJS controllers
(11 answers)
Closed 2 years ago.
i have tow controller in angularjs. if one controller change data other controller display updated data. in fact first controller has a event that it occur second controller display it. for this propose i wrote a service. this service has tow function. here is my service code.
app.service('sharedData', function ($http) {
var data=[]
return {
setData: function () {
$http.get('/getData').success(function(response){
data = response;
})
},
getData: function(){
return data;
}
}
});
in first controller
app.controller("FirstController", function ($scope, $http,sharedData)
{
$scope.handleGesture = function ($event)
{
sharedData.setData();
};
});
in second controller:
app.controller("SecondController", function ($scope,sharedData) {
var data=[];
data = sharedData.getData();
}
);
in first controller setData work with out any problem but in second controller not work correctly. how to share data dynamically between tow controllers?
You are on the right track with trying to share data between controllers but you are missing some key points. The problem is that SecondController gets loaded when the app runs so it calls sharedData.getData() even though the call to setData in the firstController does not happen yet. Therefore, you will always get an empty array when you call sharedData.getData().To solve this, you must use promises which tells you when the service has data available to you. Modify your service like below:
app.service('sharedData', function ($http, $q) {
var data=[];
var deferred = $q.defer();
return {
setData: function () {
$http.get('/getData').success(function(response){
data = response;
deferred.resolve(response);
})
},
init: function(){
return deferred.promise;
},
data: data
}
})
And the secondController like this:
app.controller("SecondController", function ($scope,sharedData) {
var data=[];
sharedData.init().then(function() {
data = sharedData.data;
});
});
For more info on promises, https://docs.angularjs.org/api/ng/service/$q
You had multiple syntax problems, like service name is SharedData and you using it as SharedDataRange, the service is getting returned before the get function.
What I have done is corrected all the syntax errors and compiled into a plunkr for you to have a look. Just look at the console and I am getting the data array which was set earlier in the setter.
Javascript:
var app = angular.module('plunker', []);
app.controller("FirstController", function ($scope,sharedDateRange)
{
sharedDateRange.setData();
});
app.controller("SecondController", function ($scope,sharedDateRange) {
var data=[];
data = sharedDateRange.getData();
console.log(data);
});
app.service('sharedDateRange', function ($http) {
var data=[];
return {
setData: function () {
data = ['1','2','3'];
}
,
getData: function(){
return data;
}
}
});
Working Example
If you want to keep sharedDataRange as the variable name and service name as sharedData have a look at this example
javascript:
var app = angular.module('plunker', []);
app.controller("FirstController", ['$scope','sharedData', function ($scope,sharedDateRange)
{
sharedDateRange.setData();
}]);
app.controller("SecondController", ['$scope','sharedData', function ($scope,sharedDateRange) {
var data=[];
data = sharedDateRange.getData();
console.log(data);
}]);
app.service('sharedData', function ($http) {
var data=[];
return {
setData: function () {
data = ['1','2','3'];
}
,
getData: function(){
return data;
}
}
});
You can bind the data object on the service to your second controller.
app.service('sharedData', function ($http) {
var ret = {
data: [],
setData: function () {
$http.get('/getData').success(function(response){
data = response;
});
}
};
return ret;
});
app.controller("FirstController", function ($scope, sharedData) {
$scope.handleGesture = function () {
sharedData.setData();
};
});
app.controller("SecondController", function ($scope, sharedData) {
$scope.data = sharedData.data;
});
What you need is a singleton. The service sharedData needs to be a single instance preferably a static object having a static data member. That way you can share the data between different controllers. Here is the modified version
var app = angular.module('app', []);
app.factory('sharedData', function ($http) {
var sharedData = function()
{
this.data = [];
}
sharedData.setData = function()
{
//$http.get('/getData').success(function(response){
this.data = "dummy";
//})
}
sharedData.getData = function()
{
return this.data;
}
return sharedData;
})
.controller("FirstController", function ($scope, $http,sharedData)
{
sharedData.setData();
})
.controller("SecondController", function ($scope,sharedData) {
$scope.data=sharedData.getData();
});
I have removed the event for testing and removed the $http get for now. You can check out this link for a working demo:
http://jsfiddle.net/p8zzuju9/

Confusion about data usage in Controllers

How can I use the fetched data in customersController in AnotherCustomersController
function customersController($scope, $http) {
$http.get("http://www.w3schools.com//website/Customers_JSON.php")
.success(function(response) {$scope.names = response;});
}
function AnotherCustomersController($scope){
//What should I do here??
}
Full Details Here
You can share data between controllers using $rootscope but I don't think this is a best practice so my solution contain usage of angular service -> plnkr
app.factory('CustomerService', function ($http) {
return {
fetchData: function () {
return $http.get('http://www.w3schools.com//website/Customers_JSON.php')
}
}
});
app.controller('customersController', function ($scope, CustomerService) {
CustomerService.fetchData().success(function (response) {
$scope.names = response;
});
});
app.controller('AnotherCustomersController', function ($scope, CustomerService) {
CustomerService.fetchData().success(function (response) {
$scope.names = response;
});
});
Additionally i have refactor your code so only one app is used on page. If you want to use more than one you have to bootstrap them manually -> Read More

Load views after services in angularjs

In my angular app I have a view, a controller and a service.
The service load resources ex:service load persons and initialize value with the result.
I want to load my view after my service finish his function to load his resources.
var myApp = angular.module('myApp',[]);
myApp.controller('PersonsCtrl', ($scope, Persons) {
$scope.persons = Persons.data;
});
myApp.factory('Persons', {
data: [[function that load resources => take time]]
});
So I want to load my controller when my service finish his initialization.
Some ideas?
Assuming you have a route provider, here's a basic example. When the promise is resolved, "personData" will be injected into your controller. There's not much info about what your service does, so I had to give something very generic.
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/persons', {
controller: 'PersonsCtrl',
templateUrl: 'persons.html',
resolve: {
personData: ['Persons', function(Persons) {
return Persons.getData();
}]
}
});
}]);
myApp.controller('PersonsCtrl', ($scope, personData) {
$scope.persons = personData;
});
myApp.factory('Persons', {
getData: function() {//function that returns a promise (like from $http or $q)};
});
Maybe try using promises, example below
var myApp = angular.module('myApp',[]);
myApp.controller('PersonsCtrl', ($scope, Persons) {
$scope.persons = Persons.getData().then(function(response){
//do whatever you want with response
});
});
myApp.factory('Persons', function ($http, $q) {
return {
getData: function () {
var def = $q.defer();
$http.get('url').
success(function (response) {
def.resolve(response);
})
return def.promise();
}
}
});

Passing argument(s) to a service in AngularJs

I am trying to configure my first tidbits of the AngularJs for a trivial stuff, but unfortunately unsuccessful at it after considerable amount of time.
My Premise:
Users select one of the options from a dropdown and have an appropriate template loaded into a div below the select. I have set up the service, a custom directive (by following the ans by #Josh David Miller on this post, and a controller in place. The ajax call in service is working fine except that the params that I pass to the server is hardcoded. I want this to be the 'key' from the dropdown selected by user. At the moment I am failing to have this code passed to the service.
My configuration:
var firstModule = angular.module('myNgApp', []);
// service that will request a server for a template
firstModule.factory( 'katTplLoadingService', function ($http) {
return function() {
$http.get("${createLink(controller:'kats', action:'loadBreedInfo')}", {params:{'b1'}}
).success(function(template, status, headers, config){
return template
})
};
});
firstModule.controller('KatController', function($scope, katTplLoadingService) {
$scope.breed = {code:''}
// here I am unsuccessfully trying to set the user selected code to a var in service,
//var objService = new katTplLoadingService();
//objService.breedCode({code: $scope.breed.code});
$scope.loadBreedData = function(){
$scope.template = katTplLoadingService();
}
});
firstModule.directive('showBreed', function ($compile) {
return {
scope: true,
link: function (scope, element, attrs) {
var el;
attrs.$observe( 'template', function (tpl) {
if (angular.isDefined(tpl)) {
el = $compile(tpl)(scope);
element.html("");
element.append(el);
}
});
}
};
})
and the HTML setup is
<form ng-controller="KatController">
<select name="catBreeds" from="${breedList}" ng-change="loadBreedData()"
ng-model="breed.code" />
<div>
<div show-breed template="{{template}}"></div>
</div>
</form>
I need the currently hardcoded value 'b1' in the $http ajax call to be the value in $scope.breed.code.
Your ajax request is async while your controller behaves as if the request were sync.
I assume that the get request has everything it needs to perform right.
First pass a callback to your service (note the usage of fn):
firstModule.factory( 'katTplLoadingService', function ($http) {
return {
fn: function(code, callback) { //note the callback argument
$http.get("${createLink(controller:'kats', action:'loadBreedInfo')}",
params:{code: code}}) //place your code argument here
.success(function (template, status, headers, config) {
callback(template); //pass the result to your callback
});
};
};
});
In your controller:
$scope.loadBreedData = function() {
katTplLoadingService.fn($scope.breed.code, function(tmpl) { //note the tmpl argument
$scope.template = tmpl;
});
}
Doing so your code is handling now your async get request.
I didn't test it, but it must be doing the job.
I think you defined the factory not in right way. Try this one:
firstModule.factory('katTplLoadingService', ['$resource', '$q', function ($resource, $q) {
var factory = {
query: function (selectedSubject) {
$http.get("${createLink(controller:'kats', action:'loadBreedInfo')}", {
params: {
'b1'
}
}).success(function (template, status, headers, config) {
return template;
})
}
}
return factory;
}]);
firstModule.controller('KatController', function($scope, katTplLoadingService) {
$scope.breed = {code:''}
$scope.loadBreedData = function(){
$scope.template = katTplLoadingService.query({code: $scope.breed.code});
}
});

Resources