How can I move this function from the controller into a separate file?
It might be a simple question but I tried to do that with services and factories but I keep doing something wrong regarding dependency injection or the syntax of the service or factory.
This is the controller:
angular.module("myApp", [])
.controller('myAppCtrl', function ($scope, $http) {
(function() {
//the function to be moved
//do somthing
})();
$scope.data = {};
$http.//......do something else
});
plunkr: (Replaced real API link at request of OP)
HTML:
<div ng-app="myApp">
<div ng-controller="myAppCtrl">
<ul>
<li ng-repeat="product in data.products" ng-bind="product.name"></li>
</ul>
</div>
</div>
Javascript:
angular.module("myApp", [])
.constant("dataUrl", "https://some-link.com")
.controller('myAppCtrl', function($scope, corsService) {
$scope.data = {};
corsService.getData().then(function(data) {
$scope.data.products = data;
}).catch(function(error) {
$scope.data.error = error;
});
});
angular.module("myApp")
.factory('corsService', function($http, dataUrl) {
return {
getData: getData
}
function corsRequestEnabler() {
//Enable CORS requests
};
function getData() {
corsRequestEnabler();
return $http.get(dataUrl)
.then(function(response) {
console.log('Response', response);
return response.data;
}, function(error) {
return error
})
}
});
var app=angular.module("myApp", []);
app.controller('myAppCtrl', function (corsService, $scope, $http, dataUrl ) {
corsService();
app.factory('corsService' ,function($http){
var data = {};
$http.get(dataUrl)
.success(function (data) {
data.products = data;
console.log(data);
})
.error(function (error) {
data.error = error;
});
return data;
});
});
Related
I am new to this field so need help.I have to post data to API but i am unable to do this.Please help me and let me now the process.
API is: http://trendytoday.in/ers/api/DeviceAlarms
And JSOn format in which i have to send data is:
{
"ers": {
"agency_device_id": "1"
}
}
AngularJS provides the $http service, which has a method most. This can be used like:
var app = angular.module("app", []);
app.controller("HttpGetController", function($scope, $http) {
$scope.SendData = function() {
var data = {
"ers": {
"agency_device_id": "1"
}
}
$http.post('http://trendytoday.in/ers/api/DeviceAlarms', data)
.then(function(res) {
console.log(res);
}, function(err) {
console.error(err);
})
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="HttpGetController">
<button ng-click="SendData()">Submit</button>
<hr /> {{ PostDataResponse }}
</div>
This should be called from a controller or a service, and whichever you choose should have the $http service included as a dependency.
.controller('AppCtrl', function($scope, $http) {
$scope.ers = {
'agency_device_id' : ''
};
$scope.submit = function(){
var link = 'http://trendytoday.in/ers/api/DeviceAlarms';
$http.post(link, {ers: $scope.ers},{headers: {'Content-Type': 'application/json'} }).then(function (res){
$scope.mssg = res.data.ers.resMessage;
$scope.resp = res.data.ers.response;
I have a log in screen that when the user enters the correct credentials will be able to get JSON data. For now I don't have a real API link. I'm just using dummy JSON data from a script file. The loginCtrl will pass parameters to the 'dummydata' factory which will make a 'GET' request. On success, the factor will pass the JSON data to the 'useData' function in the factory. This function in the factory is what all the controllers in my ng-view use.
The problem that I am having is that all the other controllers are calling 'dummyData.dashboardsData' and getting undefined because no one has logged in to pass data to that function. How can I prevent controllers (for example, navCtrl) from calling the factory until someone has logged in?
This is my index file:
<body ng-app="ciscoImaDashboardApp" ng-style="{'background-image': backgroundImg}" ng-controller="loginCtrl">
<login></login>
<div ng-view></div>
<menu></menu>
</body>
This is my factory:
angular.module('ciscoImaDashboardApp').factory('dummyData', ['$q', '$http', function($q, $http) {
var apiServices = {};
apiServices.login = function(user,password,callback) {
$http({method: 'GET', url: 'scripts/services/dummydata.js'})
.success(function (response) {
dataStatus = response.success;
apiServices.useData(response);
callback(dataStatus);
})
.error(function(error) {
console.log("There was an error: " + error);
});
};
apiServices.useData = function(response) {
var data = response.data;
apiServices.dashboardsData = data;
}
return apiServices;
}]);
This is my navCtrl:
angular.module('ciscoImaDashboardApp')
.controller('navCtrl', function($scope, navService, $location, dummyData) {
var data = dummyData.dashboardsData;
});
This is my loginCtrl:
angular.module('ciscoImaDashboardApp')
.controller('loginCtrl', function ($scope, $rootScope, dummyData, $location) {
$scope.login = function() {
var user_email = $scope.email;
var user_password = $scope.password;
dummyData.login(user_email, user_password, function (dataStatus) {
if (dataStatus) {
console.log("Success!");
$scope.loggedIn = true;
$location.path('/welcome');
} else {
console.log("Error");
}
});
}
});
angular.module('alertApp', [
'alertApp.controllers',
'alertApp.services'
]);
angular.module('alertApp.services', []).
factory('alertAPIservice', function($http) {
var alertAPI = {};
alertAPI.getAlerts = function() {
return $http({
method: 'JSONP',
url: 'http://localhost:50828/api/alert'
});
}
return alertAPI;
});
angular.module('alertApp.controllers', [])
.controller('mainController', function($scope, alertAPIservice) {
$scope.message = 'Hello Mid-World!';
$scope.alertsList = [];
alertAPIservice.getAlerts().success(function (response) {
$scope.alertsList = response;
});
});
My app runs fine without errors and I can see the $scope.message displayed on the page. In fiddler I can see that my api call returns a 200 message, but the success function is never called. What have I done wrong
UPDATE
I Changed to:
alertAPIservice.getAlerts().then(function successCallback(response) {
$scope.alertsList = response;
}, function errorCallback(response) {
console.log("turd");
});
And although I receieve a 200 in fiddler, the error callback is called. The response is from web api and is of type Ok();
You need to use the name of the callback as "JSON_CALLBACK".
Please refer your updated code as below -
angular.module('alertApp', ['alertApp.controllers','alertApp.services']);
angular.module('alertApp.services', []).factory('alertAPIservice', function($http) {
var alertAPI = {};
alertAPI.getAlerts = function() {
return $http.jsonp('https://angularjs.org/greet.php?name=StackOverflow&callback=JSON_CALLBACK');
//use &callback=JSON_CALLBACK' in url
}
return alertAPI;
});
angular.module('alertApp.controllers', [])
.controller('mainController', function($scope, alertAPIservice) {
$scope.message = 'Hello Mid-World!';
$scope.alertsList = "loading data";
alertAPIservice.getAlerts().then(function (response) {
$scope.alertsList = response.data;
},function(error,a,b){
$scope.alertsList = error;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="alertApp">
<div ng-controller="mainController">
{{message}}
<div>
<pre>{{alertsList|json}}</pre>
</div>
</div>
</body>
you can refer jsonp documentation here.
Hope this helps you!
Try this one ('then' instead of 'success' ):
alertAPIservice.getAlerts().then(function (response) {
$scope.alertsList = response;
});
I'm approaching AngularJS and I want to get data from a database. I succeeded in doing this
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, $http) {
$http.get("backListaUtenti.php").success(function(data) { $scope.utenti=data } )
});
but I'd like to use a factory / service in order use the data from multiple controllers (but is not working)
angular.module("myApp")
.factory("utentiService", function($http,$q) {
var self = $q.defer();
$http.get("backListaUtenti.php")
.success(function(data){
self.resolve(data);
})
.error(function(){
alert("Error retrieving data!");
})
return self.promise;
});
angular.module("myApp")
.controller("utenteCtrl", function($scope, $routeParams, utentiService, filterFilter) {
var userId = $routeParams.userId;
$scope.utente = filterFilter(utentiService.utenti, { id: userId })[0];
});
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, utentiService) {
$scope.utenti = utentiService.utenti;
});
Where am I failing?
The problem is in your service implementation. Here is your code refactored:
angular.module("myApp")
.factory("utentiService", function($http) {
return {
getData: function () {
return $http.get("backListaUtenti.php").then(function (response) {
return response.data;
});
}
};
});
angular.module("myApp")
.controller("utenteCtrl", function($scope, $routeParams, utentiService, filterFilter) {
var userId = $routeParams.userId;
utentiService.getData().then(function(data) {
$scope.utente = filterFilter(data, { id: userId })[0];
});
});
angular.module("myApp")
.controller("listaUtentiCtrl", function($scope, utentiService) {
utentiService.getData().then(function (data) {
$scope.utenti = data;
});
});
If your data is static you can cache the request and avoid unnecessary requests like this:
$http.get("backListaUtenti.php", { cache: true });
In an AngularJs application, we need to fetch a config json from server. This config is used in several controllers, and there are many controllers will retrieve another resources based on the config.
For now, I'm doing it like this:
angular.module('myApp', [])
.run(function($http, $rootScope) {
$http.get('/public/js/config.json')
.success(function(data) {
$rootScop.config = data;
})
}
.controller('Controller1', function($http, $scope, $rootScope) {
$scope.$watch('config', function() {
if($rootScope.config) {
$http.get('/public/data/' + $rootScope.config.dataSource1 + ".json")
.success(funciton(data) {
$scope.mydata1 = data;
})
}
});
})
.controller('Controller2', function($http, $scope, $rootScope) {
$scope.$watch('config', function() {
if($rootScope.config) {
$http.get('/public/data/' + $rootScope.config.dataSource2 + ".json")
.success(funciton(data) {
$scope.mydata2 = data;
})
}
});
})
You can see I used $watch to watch the $rootScope.config and do something based on it.
It works but I find the code is not very good. Is there any better solution?
PS: We are not using angular routes in this project.
Instead of watching the $rootScope, you could use a service like this:
angular.module('myApp', [])
.factory('appConfig', function ($http) {
return $http.get('/public/js/config.json')
.then(function (resp) {
return resp.data;
});
})
.controller('Controller1', function($http, $scope, appConfig) {
appConfig.then(function (config) {
$http.get('/public/data/' + config.dataSource1 + ".json")
.success(function (data) {
$scope.mydata1 = data;
});
});
})
.controller('Controller2', function($http, $scope, appConfig) {
appConfig.then(function (config) {
$http.get('/public/data/' + config.dataSource2 + ".json")
.success(funciton(data) {
$scope.mydata2 = data;
});
});
});
Hope this helps.