AngularJS - How can I get data from GET method - javascript

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);
}
};
});

Related

Fill angularjs scope with a dynamic array

My Angular App works with
<script>
var app = angular.module('MyApp', []);
app.controller('myCtrl', function ($scope, $sce) {
$scope.urls = [
{
"url": $sce.trustAsResourceUrl("https://www.youtube.com/watch?v=KhzGSHNhnbI")
},
{
"url": $sce.trustAsResourceUrl("https://www.youtube.com/watch?v=OPxeCiy0RdY")
}
]
});
</script>
But it doesn't work with
<script>
urls = [
{
"url":"https://www.youtube.com/watch?v=KhzGSHNhnbI"
},
{
"url":"https://www.youtube.com/watch?v=OPxeCiy0RdY"
}
]
</script>
<script>
var app = angular.module('MyApp', []);
app.controller('myCtrl', function ($scope, $sce) {
function myUrl(url) {
this.url = url;
}
$scope = [];
urls.forEach(function (url, i) {
$scope.push(new myUrl($sce.trustAsResourceUrl(url)));
});
});
</script>
Update: still doesn't work
<script>
var app = angular.module('MyApp', []);
app.controller('myCtrl', function ($scope, $sce) {
function myUrl(url) {
this.url = url;
}
$scope.urls = [];
urls.forEach(function (url, i) {
$scope.urls.push(new myUrl($sce.trustAsResourceUrl(url)));
});
});
</script>
Error: [$sce:itype] http://errors.angularjs.org/1.4.3/$sce/itype?p0=resourceUrl
replace $scope.push(new myUrl($sce.trustAsResourceUrl(url))); with
$scope.push(new myUrl($sce.trustAsResourceUrl(url.url)));
https://plnkr.co/edit/tpl:FrTqqTNoY8BEfHs9bB0f?p=preview
urls = [
{
"url":"https://www.youtube.com/watch?v=KhzGSHNhnbI"
},
{
"url":"https://www.youtube.com/watch?v=OPxeCiy0RdY"
}
]
var app = angular.module('plunker', []);
app.controller('MainCtrl', function ($scope, $sce) {
function myUrl(url) {
this.url = url;
}
$scope.urls = [];
urls.forEach(function (url, i) {
$scope.urls.push(new myUrl($sce.trustAsResourceUrl(url.url)));
});
});
<!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 ng-repeat="url in urls">Hello {{url.url}}!</p>
</body>
</html>

Get new name to show in angular scope

I have a simple angular controller to post a new name and display the name on the page.
The problem is I cant see the name and the rest of the details to show in the scope ....
Any idea how to fix this and why its not working ?
HTML
<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
<meta charset="UTF-8">
<title>Angular Base64 Upload Demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/adonespitogo/angular-base64-upload/master/src/angular-base64-upload.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div ng-controller="UpLoadImage">
<div ng-repeat="step in stepsModel">
<img class="thumb" ng-src="{{step}}"/>
</div>
<label for="file">Select File</label>
<input type='file' name='file' base-sixty-four-input required onload='onLoad' maxsize='600'
accept='image/*' ng-model-instant onchange='angular.element(this).scope().imageUpload(this)'/>
</div>
<div ng-controller="PostData">
{{items.c_name}}
<form ng-submit="sendPost()">
<input ng-model="newName"/>
<button type="submit">Send Data</button>
</form>
</div>
</body>
</html>
App.js
angular.module('myApp', ['naif.base64'])
.controller('UpLoadImage', function ($scope, $http, $window, $rootScope) {
$scope.imageUpload = function (element) {
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(element.files[0]);
};
$scope.imageIsLoaded = function (e) {
$scope.$apply(function () {
$scope.stepsModel.push(e.target.result);
});
$scope.onLoad = function (e, reader, file, fileList, fileOjects, fileObj) {
alert('image uploaded');
};
};
$scope.stepsModel = [];
})
.controller('PostData', function ($scope, $http) {
$scope.items = {
c_name: "Campaign name here",
max_slots: 5,
slots: [
{
slot_id: 1,
base_image: "base 64 image"
}
]
};
$scope.newName = "Enter name";
$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
c_name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.items = data;
})
}
});
You missed ng-model property in base-sixty-four-input directive input:
angular.module('myApp', ['naif.base64'])
.controller('UpLoadImage', function ($scope, $http, $window, $rootScope) {
$scope.imageUpload = function (element) {
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(element.files[0]);
};
$scope.imageIsLoaded = function (e) {
$scope.$apply(function () {
$scope.stepsModel.push(e.target.result);
});
$scope.onLoad = function (e, reader, file, fileList, fileOjects, fileObj) {
alert('image uploaded');
};
};
$scope.stepsModel = [];
})
.controller('PostData', function ($scope, $http) {
$scope.items = {
c_name: "Campaign name here",
max_slots: 5,
slots: [
{
slot_id: 1,
base_image: "base 64 image"
}
]
};
$scope.newName = "Enter name";
$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
c_name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.items = data;
})
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" ng-app='myApp'>
<head>
<meta charset="UTF-8">
<title>Angular Base64 Upload Demo</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script type="text/javascript" src="//cdn.rawgit.com/adonespitogo/angular-base64-upload/master/src/angular-base64-upload.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body>
<div ng-controller="UpLoadImage">
<div ng-repeat="step in stepsModel">
<img class="thumb" ng-src="{{step}}"/>
</div>
<label for="file">Select File</label>
<input ng-model="file" type='file' name='file' base-sixty-four-input required onload='onLoad' maxsize='600'
accept='image/*' ng-model-instant onchange='angular.element(this).scope().imageUpload(this)'/>
</div>
<div ng-controller="PostData">
{{items.c_name}}
<form ng-submit="sendPost()">
<input ng-model="newName"/>
<button type="submit">Send Data</button>
</form>
</div>
</body>
</html>
Are you sure property c_name exists on the data returned by the $http.post ? . Add a console log to print what you really get. You also have to ensure there is no error by setting an error callback. I also suggest to give a name other than data for the result (res instead of data for example):
var data = {}; // There is already a variable named data here
$http.post("/echo/json/", data).success(function(res, status) {
$scope.items = res;
console.log("$scope.items: ", $scope.items);
}, function() { console.log("There is an error"); })
Add ng-modal to input where you used base-sixty-four-input directive.
Add cdn path of jquery.

angularjs resource error a.push is not a function

I cant save the uploaded file name and format through json value. I'm getting response but I can't save and update in json file sample_data.json. its showing an error:
TypeError: a.push is not a function
Please help me.
Error:
Thanks in advance.
Html
<!DOCTYPE html >
<html ng-app='uploadfiles'>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title>Upload files</title>
</head>
<body ng-controller="uploadCtrl">
<div class="container" >
<form >
<input type="file" ng-file-model="files" multiple model="model" />
<button type="button" ng-click="upload()">Upload</button>
</form>
<p ng-repeat="file in files">
{{file.name}}
</p>
<div id="result">
<p>{{msg}}</p>
</div>
</div>
<script src="lib/angular.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-resource.min.js"></script>
<script src="app/app.js" type="text/javascript"></script>
<script src="app/controller.js" type="text/javascript"></script>
<script src="app/directives.js" type="text/javascript"></script>
</body>
</html>
app.js
var uploadApp = angular.module('uploadfiles',['ngResource', 'myAppServices']);
controller.js
uploadApp.controller('uploadCtrl',['$scope','uploaddata', function($scope, uploaddata, $http) {
$scope.files =[];
$scope.upload=function(){
uploaddata.save($scope.files, function(data) {
$scope.msg ='file saved';
});
};
}]);
var myAppServices = angular.module('myAppServices', ['ngResource']);
myAppServices.factory('uploaddata', ['$resource',
function($resource) {
return $resource('../uploadfiles/temp/sample_data.json', {}, {});
}
]);
Directive.js
uploadApp.directive('ngFileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.ngFileModel);
var isMultiple = attrs.multiple;
var modelSetter = model.assign;
element.bind('change', function () {
var values = [];
angular.forEach(element[0].files, function (item) {
var value = {
// File Name
name: item.name,
//File Size
size: item.size,
type: item.type,
//File URL to view
url: URL.createObjectURL(item),
// File Input Value
_file: item
};
values.push(value);
});
scope.$apply(function () {
if (isMultiple) {
modelSetter(scope, values);
} else {
modelSetter(scope, values[0]);
}
});
});
}
};
}]);
by default, resource expects an object as result, not an array;
try setting the resource option: "isArray: true"

Pass a variable from controller into headers ngResource

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>

Request REST service

I am currently at beginner level at javascript and angular.js framework.
My problem is that I cannot make ngResource working .
Plunker
My code:
JS:
var geolocationControllers = angular.module('geolocationControllers', ['ngResource']);
geolocationControllers.controller('geolocationControllers', ['$scope', '$resource',
function($scope, $resource) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$scope.$apply(function() {
$scope.position = $resource('http://nominatim.openstreetmap.org/reverse?format=json', {}, {
query: {
method: 'GET',
params: {
lat: position.coords.latitude,
lon: position.coords.longitude
}
}
});
console.log($scope.position);
});
});
}
}
]);
HTML:
<div class="container" ng-controller="geolocationControllers">
<label for="location">Your location:</label>
<input type="text" id="location" size="120" ng-model="position"/>
</div>
This outputs to console and is also in input element:
function Resource(value) { shallowClearAndCopy(value || {}, this); }
You can do something like this... This will work, I tested it in my browser... you will have to rename the parts you need to...
HTML
<!DOCTYPE HTML>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>untitled</title>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</head>
<body ng-controller="myController">
<label for="location">Your location:</label><br>
<input type="text" id="location" size="120" ng-model="positionText"/>
</body>
</html>
And Javascript
var myApp = angular.module('myApp', []);
myApp.controller('myController', function ($scope, $http) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (curPosition) {
var curLongi = curPosition.coords.longitude;
var curLati = curPosition.coords.latitude;
$http.get('http://nominatim.openstreetmap.org/reverse?format=json&lat='+curLati.toString()+'&lon='+curLongi.toString()).success(function (data) {
alert(JSON.stringify(data));
$scope.positionText = data.display_name;
});
});
}
});

Categories

Resources