Pass a variable from controller into headers ngResource - javascript

I am trying to set a header value based on the value in my controller. I have the header sending when I am hard coding it as shown below but how can I pass the value from the controller into the ngResource get request,
eg I want the value of anything in the headers to be the value from my controller.
var app = angular.module('app', ['ngResource']);
app.factory('UserService', function ($resource) {
return $resource('http://jsonplaceholder.typicode.com/users/:user',{user: "#user"},{
get: {
method: 'GET',
headers: { 'something': 'anything' }
}
});
});
app.controller('TestCtrl', function($scope, $resource, UserService) {
$scope.test = "text";
UserService.get({
user: 2
}, function(data) {
$scope.id = data.id;
}, function(err) {
console.log(err);
});
});
<!doctype html>
<html ng-app="app">
<head>
<meta charset="utf-8">
<title ng-bind="title" ng-cloak>Restaurant</title>
</head>
<body ng-controller="TestCtrl">
id - {{id}}
<!-- Don't forget to load angularjs AND angular-resource.js -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular-resource.js"></script>
<!--Controllers-->
</body>
</html>

Related

(AngularJS) Can't inject factory into controller

I'm trying to inject my factory into a controller. If I list the factory as one of the controller's parameters, I get this error:
Error: [$injector:unpr] Unknown provider: wordRushFacProvider <- wordRushFac <- wordrushCtrl
http://errors.angularjs.org/1.6.1/$injector/unpr?p0=wordRushFacProvider%20%3C-%20wordRushFac%20%3C-%20wordrushCtrl
Here is the code for my factory:
(function() {
"use strict";
angular
.module("wordrush")
.factory("wordRushFac", function($http) {
function getValidWords() {
return $http.get('../data/valid-words.txt');
}
return {
getValidWords : getValidWords
}
})
})
And the code for my controller:
(function() {
'use strict'
angular
.module('wordrush')
.controller('wordrushCtrl', function($scope, $http, wordRushFac) {
wordRushFac.getValidWords().then(function(words) {
$scope.words = words.data;
});
$scope.words = 'Hello'
});
})();
And for my index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Word Rush</title>
<link rel="stylesheet" href="node_modules/angular-material/angular-material.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="node_modules/angular/angular.js"></script>
<script src="scripts/app.js"></script>
<script src="components/wordrush.ctr.js"></script>
<script src="components/wordrush.fac.js"></script>
</head>
<body ng-app="wordrush" ng-controller="wordrushCtrl">
<h1> {{ words }} </h1>
</body>
</html>
And for my app.js:
angular
.module('wordrush', ['ngMaterial'])
.config(function($mdThemingProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('blue')
.accentPalette('green');
})
I made a program with code identical to this except the names and variables were changed, and it worked fine. So what am I doing wrong here?
Here is a plunkr that says "Hello": https://plnkr.co/edit/MyxcXQ8YI4QYqeFsyVJz?p=preview
You have an extra set of open / close parenthesis in your controller definition, remove those:
angular
.module('wordrush')
.controller('wordrushCtrl', function($scope, $http, wordRushFac) {
wordRushFac.getValidWords().then(function(words) {
$scope.words = words.data;
});
$scope.words = 'Hello'
});
Also, are you sure you are including the ng-material JS file? I didn't see that listed in your HTML.
You're not injecting in the controller, should be:
.controller('wordrushCtrl', ['$scope', '$http', 'wordRushFac', function($scope, $http, wordRushFac) {
// Rest of controller code;
}]);
Switch your scripts. Factory script should be first then controller
Ther order should be,
<script src="scripts/app.js"></script>
<script src="components/wordrush.fac.js"></script>
<script src="components/wordrush.ctr.js"></script>
DEMO
I made the following changes and it worked fine.
(function() {
"use strict";
angular
.module("wordrush")
.factory("wordRushFac", function($http) {
function getValidWords() {
return $http.get('../data/valid-words.txt');
};
return {
getValidWords : getValidWords
};
});
}());

Angularjs Factory is undefined in controller

I am new in angular js, now I am trying to use factory to make code clearer. But now I am getting the following error:
$injector:unpr(Unknown provider).
I stuck here and cant find where is the problem. Service and this controller were in different files actually, then I tried to put them together, but still it doesnt work. I will be very glad if you will help me to find out my problem.
var app = angular.module('myApp', ['ngRoute']);
app.factory('AuthenticationService', ['$scope', '$location', function($scope, $location){
var currentUser;
return {
login: function(username, password){
var endPoint = "http://localhost:8080/RestServer/main/just/Authorize";
var jsonData = {
username: username,
password: password
};
var jsonString = JSON.stringify(jsonData);
$http.post(endPoint, jsonString,{headers: {'Content-Type': 'application/json'}}).success(function (data,status, headers ){
if(data.access == "ok")
{
$location.path("learning");
}
else
{
$location.path("error");
}
});
},
logout: function(){},
isLoggedIn: function(){},
curUser: function(){return currentUser}
};
}
]);
app.controller('loginController',['$scope', 'AuthenticationService', function($scope, AuthenticationService)
{
$scope.login = function()
{
AuthenticationService.login($scope.username, $scope.password);
}
}]);
Here is html:
<html data-ng-app="myApp">
<head>
<script src="https://code.angularjs.org/1.5.0-rc.0/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular-route.min.js"></script>
<script src="Scripts/app.js"></script>
<script src="Scripts/services.js"></script>
<script src="Scripts/controllers.js"></script>
<link href="CSS/bootstrap.min.css" rel="stylesheet">
<title>Welcome!</title>
</head>
<body>
<div class="container theme-showcase" role="main" ng-view="">
</div>
</body>
Just remove $scope from your factory, You don't typically use $scope inside a factory, service or provider,also add $http as a dependency since you are making a $http call
app.factory('AuthenticationService', [ '$location','$http', function( $location,$http){
}
Here is the working Application

How do I get data via an API using Angular?

I'm trying angular for the first time to get a list of accounts from an API and display it in a simple list. The api is on a separate domain. So far I have the following in my app.js
var myApp = angular.module("myApp", []);
myApp.controller("myController", function($scope){
// when landing on the page, get all todos and show them
$http.get('http://api.example.com/accounts')
.success(function(data) {
$scope.accounts = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
});
And my index.html
<!DOCTYPE html>
<html>
<script src="bower_components/angular/angular.js"></script>
<script src="app/app.js"></script>
<body ng-app="myApp" ng-controller="myController">
<ul ng-repeat="account in accounts">
<li >
{{ account.name }}
</li>
</ul>
</body>
And a sample response.
[
{
"name": "Discover",
"_id": "55d532da7fc30ff81f000008",
"__v": 0
},
{
"name": "Citi",
"_id": "55d6b9967fc30ff81f000009",
"__v": 0
}
]
I don't seem to get it to work. All I get is a blank page and the console shows this error in chrome:
'mainController()' is not a function, got undefined
You controller should look like as below : You have missed some dependencies.
myApp.controller("myController", function ($scope, $http) {
// when landing on the page, get all todos and show them
$http.get('http://api.example.com/accounts')
.success(function (data) {
$scope.accounts = data;
console.log(data);
})
.error(function (data) {
console.log('Error: ' + data);
});
});
There may be issue with cross origin request if your app and rest and on different domains.
Let me know the output in your browser's console.
Your application should look like as below :
/**
* #name myApp
*
* Lets create angular application module
* if second parameter is passed with enpty array [] or with dependecies , is * called angular module setter
*
* angular.module('myApp', []); Setter
* angular.module('myApp'); Getter
*/
angular
.module('myApp', []);
/**
* Lets create controlller
*/
angular
.module('myApp')
.controller('myController', ['MainFactory', '$scope',
function(MainFactory, $scope) {
getAllAcounts();
function getAllAcounts() {
MainFactory.getAccounts().success(function(data) {
$scope.accounts = data;
console.log(data);
}).error(function(data) {
console.log('Error: ' + data);
});
}
}
]);
/**
* Lets create factory
*/
angular
.module('myApp')
.factory('MainFactory', ['$http',
function($http) {
var factory = factory || {};
factory.getAccounts = function() {
return $http.get('http://api.example.com/accounts');
};
return factory;
}
]);
HTML :
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link data-require="bootstrap#3.3.5" data-semver="3.3.5" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script data-require="jquery#2.0.0" data-semver="2.0.0" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script data-require="bootstrap#3.3.5" data-semver="3.3.5" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script src="app.js"></script>
</head>
<body ng-controller="myController">
<ul ng-repeat="account in accounts">
<li>
{{ account.name }}
</li>
</ul>
</body>
</html>

AngularJS - How can I get data from GET method

My Controller:
angular.module('apartmentCtrl', [])
.controller('ApartmentController', function ($scope, $http, Apartment) {
$scope.loading = true;
$scope.myLocation = '';
Apartment.get($scope.myLocation).success(function (data) {
$scope.apartments = data;
$scope.loading = false;
});
});
My Service
angular.module('apartmentService', [])
.factory('Apartment', function ($http) {
return {
get: function (myLocation) {
//return $http.get('/api/apartments');
return $http({
method: 'GET',
url: '/api/apartments',
//headers: {'Content-Type': 'application/x-www-form-urlencoded'},
params: {location: myLocation}
});
}
};
});
My HTML:
<input type="text" name="myLocation" class="form-control" ng-model="myLocation">
How can I get data from GET method by AngularJS and pass it to params
If you want to pass some value from your form as "location", you should bind it to your model, and explicitly pass it to your factory get function.
I have a working example here, it just does a window alert showing you the typed in data, in place of the $http call, but the idea is the same.
http://plnkr.co/edit/fRra6RfQrSZb8rzrm4XF?p=preview
Html:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<form ng-submit="getIt()">
<input type="text" ng-model="myLocation"/>
<input type="submit"/>
</form>
</body>
</html>
Javascript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, Apartment) {
$scope.name = 'World';
$scope.myLocation = 'Hollywood';
$scope.getIt = function() {
Apartment.get($scope.myLocation);
}
});
app.factory('Apartment', function ($window) {
return {
get: function (whatLocation) {
$window.alert(whatLocation);
}
};
});

angular.js and node.js calling node on page load

I am trying to call a node function when loading a page with angular, but for some reason the function does not get called. I have the ng-app and controller specified and I figured I would just put the api call in the controller constructor. Here is the code for the page:
<!doctype html>
<!-- ASSIGN OUR ANGULAR MODULE -->
<html ng-app="landingPage">
<head>
<!-- META -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><!-- Optimize mobile viewport -->
<title>my page</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="core.js"></script>
</head>
<!-- SET THE CONTROLLER AND GET ALL GATEWAYS -->
<body ng-controller="mainController">
And then my core.js file is in the same directory which holds the controller has the controller:
var loadingCtrl = angular.module('landingPage', []);
function mainController($scope, $http) {
console.log('loading gateways');
// when landing on the page, get all gateways and show them
$http.get('/api/gateways')
.success(function(data) {
$scope.gateways = data;
console.log('got response');
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
}
I never see any of the log statements....
I think you just need to change
function mainController($scope, $http) {
//your code here
}
to
angular.module('landingPage').controller('mainController', function($scope, $http) {
//your code here
});
To let angular know the controller exists.
Try array notation for dependency injection like below.
angular.module('landingPage', []).controller('mainController',['$scope','$http', function($scope, $http) {
console.log('loading gateways');
// when landing on the page, get all gateways and show them
$http.get('/api/gateways')
.success(function(data) {
$scope.gateways = data;
console.log('got response');
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
}]);
Check the Plunker.
But I would suggest to use factory service for loading external data instead loading it inside controller as you can reuse the same service in different controllers.
Sample code with factory service
'use strict';
angular.module('landingPage', []).controller('mainController',['$scope','$http','gatewayService', function($scope, $http,gatewayService) {
console.log('loading gateways');
// when landing on the page, get all gateways and show them
$scope.gateways = gatewayService.getData();
}]).factory('gatewayService', ['$http',function($http){
return {
getData: function() {
return $http.get('/api/gateways')
.success(function(data) {
return data
console.log('got response');
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
return data;
});
}
};
}]);
Check Plunkr

Categories

Resources