I want to use multiple service in same controller. I can achieve with different service as mentioned below but it performs only one service
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<H1>Random Text is:</H1>
<div>{{myRandom}}</div>
<p>MuyLocation:: {{myLocation}}.</p>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http, $location) {
$http.get("http://www.randomtext.me/api/").then(function (response) {
$scope.myRandom = response.data.text_out;
$scope.myLocation= $location.absUrl();
});
});
</script>
</body>
</html>
BUT, i want to use both service in same controller as mentioned below
app.controller('myCtrl', function($scope, $http, $location) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
$scope.myUrl = $location.absUrl();
});
});
So How can we perform both services in same controller.
Thanks in advance.
I think you can solved your problem with promise chaining.
$http.get("http://www.randomtext.me/api/").then(function success(response) {
return $q.resolve(response);
}, function error() {
return $http.get("welcome.htm");
}).then(function success(response) {
$scope.myWelcome = response.data;
$scope.myUrl = $location.absUrl();
});
If call to randomapi failed, so fetch welcome.html.
Related
I need to do four $http.get call and I need to send returned $scope variable to the one HTML to print all the information. In the moment I have the next code in JS:
(function (ng) {
var mod = ng.module("serviciosAdminModule");
mod.controller('serviciosAdminCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get("api/hoteles").then(function (response) {
$scope.serviciosHotelesRecords = response.data;
});
}]);
mod.controller('serviciosAdminCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get("api/paseos").then(function (response) {
$scope.serviciosPaseosRecords = response.data;
});
}]);
mod.controller('serviciosAdminCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get("api/aseos").then(function (response) {
$scope.serviciosAseosRecords = response.data;
});
}]);
mod.controller('serviciosAdminCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get("api/entrenamientos").then(function (response) {
$scope.serviciosEntrenamientosRecords = response.data;
});
}]);
})(window.angular);
In the HTML I have the next:
<tr ng-repeat="servicio in serviciosAdminRecords">
<td id="{{$index}}-id" class="parrafoscards" style="font-size: 16px">
<a ui-sref="servicioAdminDetail({servicioId: servicio.id})">{{servicio.id}}</a>
</td>...
In the HTML I ask for serviciosAdminRecords that is the $scope variable where I want to put all the .get data
You probably need to chain the promises in order to add all the responses together into the one array. Get rid of all the different controllers - they will have separate scopes - and just have the one controller, making sure it is being used in the view by using ng-controller='serviciosAdminCtrl' as an attribute in your view.
mod.controller('serviciosAdminCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.serviciosAseosRecords = [];
$http.get("api/hoteles").then(function (response) {
$scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
$http.get("api/paseos").then(function (response) {
$scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
$http.get("api/aseos").then(function (response) {
$scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
$http.get("api/entrenamientos").then(function (response) {
$scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
});
});
});
});
}]);
If your response.data is an array of object then initialize serviciosPaseosRecords as array.
$scope.serviciosHotelesRecords = [];
instead of assigning response.data to serviciosPaseosRecords
$scope.serviciosAseosRecords = response.data
Concat response.data with existing serviciosAseosRecords array.
$scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data)
I'm pretty new to Angular. I am trying to implement a search page using star wars API but getting $scope in undefined. am not sure what am doing wrong here:
'use strict';
var app = angular.module('starApp');
/* Application controller (for top-level auth) */
app.controller('SearchController', ['$location', 'AuthenticationService',
'$scope', '$http',
function($location, AuthenticationService, $scope, $http) {
console.log('*** SearchController ***');
$scope.items = [];
(function getData() {
var apiURL = "https://swapi.co/api/planets";
axios.get(apiURL).then(function(response) {
showDetail(response.data);
});
})();
function showDetail(data) {
$scope.items = data.results;
}
}]);
I'm injecting $scope into my controller, but still it shows it is undefined.
You should use $http service. here is working snippet:
'use strict';
var app = angular.module('myApp',[]);
/* Application controller (for top-level auth) */
app.controller('SearchController', ['$location',
'$scope', '$http',
function($location, $scope, $http) {
console.log('*** SearchController ***');
$scope.items = [];
$scope.loading = false;
var apiURL = "https://swapi.co/api/planets";
$scope.loadData = function() {
$scope.loading = true;
$http.get(apiURL)
.then(function(response) {
$scope.showDetail(response.data);
$scope.loading = false;
});
};
$scope.loadData();
$scope.showDetail = function(data) {
$scope.items = data.results;
};
}
]
);
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="SearchController" ng-cloak>
<ul ng-if="items.length>0 && !loading" >
<li ng-repeat="item in items">{{item.name}}</li>
</ul>
<div ng-if="loading">Loading...</div>
</div>
I want to wait for an http response before exiting angular controller. I have written the following code. But id doesn't work as the controller still exits before the http call is returned. Can anyone help me out to fix this? Thanks in advance.
var app = angular.module('app', []);
app.factory('MyService', function ($http) {
return $http.get('/api/endpoint').then(function(res){
return res.data;
});
});
app.controller('MyController', ['$scope', '$http', 'MyService', function($scope, $http, MyService){
MyService.then(function(data){
$scope.myVarialbe = data;
})
}]);
I would write this as below.
'use strict';
(function () {
function MyService($http) {
function getService() {
var url = yourURL;
return $http({ method: 'GET', cache: false, url: url });
}
return {
getService: getService
};
}
angular.module('app')
.factory('MyService', MyService);
}());
controller code:
MyService.getService().then(function(response) {
});
You can use like this factory just return request response promise and in controller use .then on returned promise.
var app = angular.module('app', []);
app.factory('MyService', ['$http',function($http) {
return {
getData: function() {
return $http.get('/api/endpoint');
}
};
}]);
app.controller('MyController', ['$scope', '$http', 'MyService', function($scope, $http, MyService){
MyService.getData().then(function(response){
$scope.myVarialbe = response.data;
});
}]);
Use $q is better.
Eg:
app.factory('MyService', ['$http', '$q', function($http, $q) {
return {
getData: function() {
var deferred = $q.defer();
$http.get('/api/endpoint')
.then( function(resp) {
deferred.resolve( resp.data );
});
return deferred.promise;
}
};
}]);
app.controller('MyController', ['$scope', 'MyService',function($scope, MyService){
MyService.getData().then(function(data){
$scope.myVarialbe = data;
})
}]);
I am entirely new to AngularJS. The task is however simple: to parse XML file from the url and make a table out of it.
Yet somehow angular doesn't load. I searched similar questions, but neither worked. My index.html:
<!doctype html>
<html ng-app="myApp">
<head>
<title>jj</title>
<script src="~/Scripts/angular.min.js"></script>
<script src="~/Scripts/angular.intellisense.js"></script>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/myscript.js"></script>
</head>
<body>
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">Text.</p>
</div>
<div ng-controller="AppController">
<h3>for example 2+3= {{3+2}}</h3>
</div>
</div>
</body>
</html>
I should get 5 instead of 2+3 if angular is loaded?
myscript.js currently looks like:
angular.module('myApp.service', []).
myApp.factory('DataSource', ['$http', function ($http) {
return {
get: function(file,callback,transform){
$http.get(
file,
{transformResponse:transform}
).
success(function(data, status) {
console.log("Request succeeded");
callback(data);
}).
error(function(data, status) {
console.log("Request failed " + status);
});
}
}
}]);
angular.module('myApp', ['myApp.service']);
var AppController = function ($scope, DataSource) {
var SOURCE_FILE = "guitars.xml";
xmlTransform = function (data) {
console.log("transform data");
var x2js = new X2JS();
var json = x2js.xml_str2json(data);
return json.customers.customer;
};
setData = function (data) {
$scope.dataSet = data;
};
DataSource.get(SOURCE_FILE, setData, xmlTransform);
};
Can you give me some advice?
It has to do with your syntax. I believe you have 2 errors. In your myscript.js you are declaring 2 modules. In your first module you are incorrectly declaring a factory. Use .factory not myApp.factory
angular.module('myApp.service', [])
.factory('DataSource', ['$http', function ($http) {
return {
// do something
}
}]);
In your second module you declare a function called AppController instead of calling the .controller angular method. Do this instead:
angular.module('myApp', ['myApp.service'])
.controller('AppController', ['$scope', 'DataSource', function ($scope, DataSource) {
// controller code
}]);
You can accomplish your program in a sole module by using a construct similar to what follows:
var app = angular.module('myApp', []);
app.controller('AppController', function($scope, DataSource) {
// code
});
app.factory('DataSource', ['$http', function($http) {
// code
}]);
Basically, create a variable for your app module, then call controller and factory, and pass your factory into your controller.
This may be the repeated question but the workaround I found for this issue is not working in my case thats why I am posting the question.
I've following service:
appRoot.service('MyService', function($rootScope) {
var Messenger = {
Temp: "",
TempId:"",
tempMethod: function(Id) {
TempId = Id;
$rootScope.$broadcast('FirstCtrlMethod');
}
};
return Messenger ;
});
In second controller:
appRoot.controller('SecondCtrl', function ($scope, $location, MyResource, NotificationService, MyService) {
$scope.invokeFirstCtrl= function() {
var Id = '2';
MyService.tempMethod(Id);
});
In first controller:
appRoot.controller('FirstCtrl', function ($scope, $compile, $filter, $modal, $sce, $location, NotificationService, MyService) {
$scope.$on('FirstCtrlMethod', function () {
alert('I am from frist controller');
});
});
Problem: The line "$rootScope.$broadcast('FirstCtrlMethod');" is executing as expected but it is not causing to fire event "$scope.$on('FirstCtrlMethod', function () {.." in the first controller.
I've used the differenct services in many places in my app in the same way and they are workig fine, I am not understanding why it is not working here.
putting comment as an answer...
I guess the other controller which is supposed to receive the event is not yet instatiated when you are $broadcasting the event.
Please try instantiating the other controller
Please see below working example
var app = angular.module('app', []);
app.service('MyService', function($rootScope) {
var Messenger = {
Temp: "",
TempId: "",
tempMethod: function(Id) {
TempId = Id;
$rootScope.$broadcast('FirstCtrlMethod');
}
};
return Messenger;
});
app.controller('homeCtrl', function($scope, MyService) {
$scope.invokeFirstCtrl = function() {
var Id = '2';
MyService.tempMethod(Id);
};
});
app.controller('FirstCtrl', function($scope) {
$scope.$on('FirstCtrlMethod', function() {
alert('I am from frist controller');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
<button ng-click="invokeFirstCtrl()">Invoke</button>
</div>
<div ng-controller="FirstCtrl">
</div>
</div>