Angularjs first attempt at dependency injection - angularjs

I have a UserAddController and I want to be able to access a list of countries returned by a Web API. The Web API returns data fine. Here is my app.js where I get the data :
app.factory('Country', function ($resource) {
return $resource(
"/api/country/:Id",
{ Id: "#Id" },
{ "update": { method: "PUT" } });
});
This is my Controller :
var UserAddController = function ($scope, $location, service, User) {
$scope.action = "Add";
$scope.countries = service.countries;
};
I am declaring and creating a service here :
app.factory('CountryService', CountryService);
function CountryService($resource) {
return $resource(
"/api/country/:Id",
{ Id: "#Id" },
{ "update": { method: "PUT" } });
}
I am using the same code as above just for testing purposes. I am injecting this service like this :
UserAddController.$inject = ['$scope', 'CountryService'];
This is my first attempt at dependency injection and I cannot figure out where I am going wrong. The error I currently get is 'service is undefined'. I have tried passing both the service and the Country object to the Controller with the same results. Can anybody give any advice?
EDIT : In my Controller, this populates successfully with an alert in the code, but without the alert does not populate. Any reason why this is?
function CountryService($rootScope, $http) {
var self = {};
//self.countries = [{ "$id": "1", "CountryId": 1, "CountryName": "United Kingdom" }, { "$id": "2", "CountryId": 2, "CountryName": "Republic of Ireland" }, { "$id": "3", "CountryId": 3, "CountryName": "Australia" }, { "$id": "4", "CountryId": 4, "CountryName": "New Zealand" }, { "$id": "5", "CountryId": 5, "CountryName": "United States" }, { "$id": "6", "CountryId": 6, "CountryName": "France" }, { "$id": "7", "CountryId": 7, "CountryName": "Germany" }, { "$id": "8", "CountryId": 8, "CountryName": "Finland" }];
$http({
method: 'GET',
url: '/api/country'
}).success(function (data, status, headers, config) {
self.countries = data;
});
alert(self.countries);
return self;
}

You need to add other services/dependencies.
UserAddController.$inject = ['$scope',
'$location',
'CountryService',
'UserService'];
I have assumed that last dependency is a service with name 'UserService'. It's signature would be
app.factory('UserService', UserService);
Edit :
You need to instantiate a new variable.
//Inside function body
$scope.countries = service.countries;
$scope.newCountry = $scope.countries.get({Id : someId},callbackFn);
Now you have a counrtry with 'someId' in $scope.newCountry

Make sure you injected ngResource.
app = angular.module("app", ['ngResource']);
You need to inject the modules correcly
UserAddController.$inject = ['$scope', '$location', 'CountryService', 'user'];
This is quoted the doc.
You can specify the service name by using the $inject property, which
is an array containing strings with names of services to be injected.
The name must match the corresponding service ID registered with
angular. The order of the service IDs matters: the order of the
services in the array will be used when calling the factory function
with injected parameters.
I created a FIDDLE and you can try.

Related

Accessing data from a REST API in AngularJS

I have a REST api from elasticsearch. I want to retrieve the data of a specific field. That is, I want to retrieve the data in the Gender field. What I have done is I have consume the rest service in AngularJS as follows. But nothing is appearing on the browser. Can somebody help to achieve what I want to display?
angular.module("view.index", ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/menuIndex/', {
templateUrl: 'view-index/template/index.html',
controller: 'NewController',
controllerAs: 'newCtrl',
});
}])
.controller('NewController', ['$timeout', 'overlayMessage', '$location', 'userInformation', '$http', '$scope','menuService', function ($timeout, overlayMessage, $location, userInformation, $http, $scope, menuService) {
var myCtrl = this;
myCtrl.Form = {};
$http.get('http://admin:admin#localhost:9200/index1/_search?_source=Gender').
success(function(data) {
myCtrl.json = data;
});
}]);
The GET api http://admin:admin#localhost:9200/index-data/_search?_source=Gender returns me a json body like this:
{
"took": 17,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 30003,
"max_score": 1,
"hits": [
{
"_index": "index1",
"_type": "tbl",
"_id": "1",
"_score": 1,
"_source": {
"Gender": "Female"
}
},
{
"_index": "index1",
"_type": "tbl",
"_id": "2",
"_score": 1,
"_source": {
"Gender": "Male"
}
}
And in my front end, I want to access the data in the Gender field like this:
<div ng-controller="menuNsmCtrl">
<div ng-repeat="json in json">
<p>The ID is {{json.Gender}}</p>
</div>
</div>
First use then instead of success to catch the data. success is deprecated since the angular version 1.4
$http.get('http://admin:admin#localhost:9200/index1/_search?_source=Gender').
then(function(response) {
myCtrl.json = response.data;
});
}]);
now since you use controllerAs syntax you need to use the reference variable in the html also
<div ng-controller="NewController as myCtrl">
<div ng-repeat="json in myCtrl.json.hits.hits">
<p>The ID is {{json['_source'].Gender}}</p>
</div>
</div>

ngResource return a singular item

When trying to return a singular item from a mongoDB I keep getting an error telling me I am returning an array as apposed to an object. Here's my service code:
resource: $resource('http://localhost:8080/api/item/:itemId', null, {'get' : {method: 'GET'}}, {stripTrailingSlashes: false})
function getItem(itemId) {
return this.resource.get({itemId: itemId}).$promise.then(function(resource){
return resource;
});
}
The service is above is called resolve like so:
.state('cocktail', {
templateUrl: 'client/app/features/item/item/item.html',
controller: 'ItemController',
controllerAs: 'vm',
data:{
title: 'Item'
},
params:{
itemId: null
},
resolve:{
item: getItem
}
function getItem($stateParams, itemService) {
return itemService.getItem($stateParams.itemId);
}
Then in my controller:
ItemController.$inject = ['itemService', 'item'];
function ItemController(itemService, item) {
var vm = this;
vm.item = item;
}
The object that is returned in the call is:
[
{
"_id": "57586f25661d33fe21057866",
"name": "Red Velvet",
"description": "Red Velvet Description here",
"image": "red-velvet",
"__v": 0,
"gred": []
},{
"_id": "57586f25661d33fe21057884",
"name": "Red Item",
"description": "Red Velvet Item here",
"image": "red-velvet-item",
"__v": 0,
"gred": []
},
]
The error I get in my console is - [$resource:badcfg] Error in resource configuration for action get. Expected response to contain an object but got an array. I am not expecting an array but the object of the ID I pass through in the resolve. If anyone has any comments or can see what I'm doing wrong please let me know! This is bugging me and I know it's going to be a simple fix haha!

Stuck: AngularJs using factory with http call to json

I am struck and not able to understand the issue here.
I created a factory using http service call to my json file
Factory (accountInfo.json):
appRoot.factory('accountInfo', ['$http', function($http) {
return $http.get('../../accountInfo.json')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
controller(AccountsController.js)
appRoot.controller('AccountsController', ['$scope', 'accountInfo', function($scope, accountInfo){
accountInfo.success(function(data) {
$scope.rows = data;
});
$scope.totals = {
name: '',
marketValue: 0,
cash: 0,
legend: 'none'
};
for (var i = 0; i < $scope.rows.length; i++) {
$scope.totals.marketValue += $scope.rows[i].marketValue;
$scope.totals.cash += $scope.rows[i].cash;
}
$scope.addAccount = function() {
$scope.rows.push({
name: 'New Account',
marketValue: Math.random() * 100000,
cash: Math.random() * 400000,
legend: 'cyan'
});
}
}]);
My json (accountInfo.json)
[{
"name": "Brokerage Account 3",
"marketValue": 1999990,
"cash": 1995826,
"legend": "orange"
},
{
"name": "Account 3",
"marketValue": 1949990,
"cash": 1695856,
"legend": "darkorange"
},
{
"name": "Brokerage Account 1",
"marketValue": 1349990,
"cash": 1595866,
"legend": "red"
},
{
"name": "Brokerage Account 4",
"marketValue": 155990,
"cash": 160826,
"legend": "blue"
},
{
"name": "Brokerage Account 2",
"marketValue": 74560,
"cash": 19956,
"legend": "gray"
},
{
"name": "Account 4",
"marketValue": 55006,
"cash": 53006,
"legend": "salmon"
},
{
"name": "Account 13",
"marketValue": 37340,
"cash": 0,
"legend": "green"
},
{
"name": "Joint Account 1",
"marketValue": 28308,
"cash": 4167,
"legend": "darkblue"
},
{
"name": "Joint Account 2",
"marketValue": 10000,
"cash": 10000,
"legend": "teal"
}]
Error I am receiving is "$scope.rows is undefined"
Controller is not able to access $scope.rows outside success function.
Thanks :)
You need to resolve the promise in your controller, not in your factory, just return the promise:
appRoot.factory('account', ['$http', function($http) {
return {
info: function () {
return $http.get('../../accountInfo.json');
}
}
}]);
Then in your controller do:
appRoot.controller('AccountsController', ['$scope', 'account', function($scope, account){
account.info()
.success(function(data) {
$scope.rows = data;
})
.error(function(err) {
return err;
});
}]);
FYI, the success and error methods are deprecated:
The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
See: https://docs.angularjs.org/api/ng/service/$http
Use the then method:
account.info().then(
function resolved (response) {
$scope.rows = response.data;
},
function rejected (response) {
alert(response.status + ': ' + response.statusText);
}
);
Here's a working example of the concept: http://plnkr.co/edit/UtJDpvBKKYl4rBzgXYo4?p=preview
You should return a function which fetches the data when you call it like so:
appRoot.factory('accountInfo', ['$http', function($http) {
return {
fetchData: fetchData
};
function fetchData() {
return $http.get('../../accountInfo.json');
}
}]);
then in your controller you can do:
accountInfo.fetchData()
.then(
function(data) {
console.log(data);
},
function(error) {
console.log(error);
}
);
Thank you all for the help.
I solved my issues by bootstraping the app. I was not able to access my data initially since the http call was not completed.
angular.element(document).ready(function() {
angular.bootstrap(angular.element(document), ['app']);
});

AngularJS deferred $http.get response, empty array

Please help in changing this code to be able to use $http.get html, at the moment the resulting array (html_controls) is empty. However, I can see the response in the console for all the request in $http.get. Thank you.
angular.module('exodus-grid').controller('DynamicPropertiesController', ['$scope', '$http', '$templateCache', '$q', 'coreFactory',
function($scope, $http, $templateCache, $q, coreFactory) {
//$scope.DynamicProperties = 'Property being added to the controller.';
//coreFactory.fetchData('http://uat.resources.newscdn.com.au/cs/networksales/products/latest/products.json', 'products');
// TODO: Change this harcoded value to the products.json in s3
$scope.products = [{
"id": "btyb",
"label": "BTYB + Superskin",
"description": "",
"name": "btyb",
"active": true,
"properties": [{
"bannerLink": [{
"tmp_prop_name": "bannerLink",
"label": "Header Tracking Link (Desktop)",
"type": "textbox"
}],
"superskinLink": [{
"tmp_prop_name": "superskinLink",
"label": "Sideskin Tracking Link (Desktop)",
"type": "textbox"
}],
"ImgUrl": [{
"tmp_prop_name": "ImgUrl",
"label": "Header Image Url",
"type": "textbox"
}]
}]
}, {
"id": "iframe",
"label": "iframe",
"description": "",
"name": "iframe",
"active": true,
"properties": [{
"link": [{
"tmp_prop_name": "link",
"label": "iFrame source Url",
"type": "textbox"
}]
}]
}];
var requests = [];
var html_controls = [];
var product = $scope.products[0];
var properties = angular.fromJson(product.properties);
//console.log(angular.toJson(properties));
angular.forEach(properties, function(property) {
angular.forEach(property, function(item) {
//console.log(angular.toJson(property));
if (item[0].type === "textbox") {
//console.log(angular.toJson(item));
//console.log(Object.getOwnPropertyNames(property));
//console.log(Object.keys(property));
$http.get("plugins/k-plugin-exodus-grid/templates/properties/textbox.html").success(function(html) {
html = html.replace("%%label%%", item[0].label);
html = html.replace("%%scope%%", item[0].tmp_prop_name);
//console.log(html);
html_controls.push(html);
console.log(html_controls);
var deferred = $q.defer();
requests.push(deferred.promise);
console.log(deferred, deferred)
}).then(function() {
//$scope.html = html_controls;
});
}
});
});
//console.log(html_controls);
//$scope.html = html_controls;
$q.all(requests).then(function(data) {
console.log("12312312 " , data);
$scope.html = html_controls;
});
}
]);
Looks like you are trying to resolve a array of empty promises. Since it is running async, when $q.all() us called, requests[] is still empty.
Try building an array of promises and then resolve this using q.all() instead:
var requests = []; // a list of promises
angular.forEach(properties, function(property) {
angular.forEach(property, function(item) {
var promise = $http.get("/yoururl"); // $http.get returns a promise
requests.push(promise); // add to list of requests as a promise
});
});
$q.all(requests).then(function (result) {
console.log('results' + result);
});

Server always throws 403 on Angularjs ajax call in Django

Server always throws 403 in my Django app. I tried using csrf along with the data that is being posted to server, but still no luck. What am I missing ?
Here is how am invoking the $http service function
<body ng-controller="rdCtrl">
<a ng-click="saveprof()">Save</a>
<script>
var app = angular.module('rdExampleApp', ['ui.rdplot']);
app.controller('rdCtrl', function ($scope, $http) {
$scope.dataset = {
"d0": { "id": 0, "name": "Housing", "value": 18 },
"d1": { "id": 1, "name": "Travel", "value": 31.08 },
"d2": { "id": 2, "name": "Restaurant", "value": 64 },
"d3": { "id": 3, "name": "Bank", "value": 3 },
"d4": { "id": 4, "name": "Movies", "value": 10 }
};
$scope.func = function func() {
var jdata = $scope.dataset;
return jdata;
}
$scope.saveprof = function () {
//show spinner
$('.spinner').show();
$http.post('saveprof', {
data: { 'data': $scope.dataset},
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
})
.success(function (data) {
if (data == "null") {
//your code if return data empty
} else {
//your code if return data not empty
$('#message').html(data);
}
//hide spinner
$('.spinner').fadeOut();
})
.error(function (data, status, headers, config) {
console.log('error' + status);
//hide spinner in case of error
$('.spinner').fadeOut();
})
});
</script>
</body>
Edit:
I corrected it, ajax call is being invoked when I click on button - but it returns 403 error.. Access forbidden.. I have view saveprof in my django views.. and also I used csrf token.. Am not sure why server returns 403. (http:/x.x.x.x/saveprof)
What am I missing?
you have to inject $http to the controller as parameter
app.controller('rdCtrl', function ($scope, $http) { .. }

Resources