I would like to use this to show PDF in my SPA.
I tried to build a single example but it didn't work. Look this Plunker
http://plnkr.co/edit/nZAjYr?p=preview
In this example my pdf is in http://example.com/file.pdf
I really don't know where is the error, maybe it be in my controler:
angular.module('app', ['pdfjsViewer']);
angular.module('app').controller('AppCtrl', function ($scope, $http, $timeout) {
var url = 'http://example.com/file.pdf';
$scope.pdf = {
src: url, // get pdf source from a URL that points to a pdf
data: null // get pdf source from raw data of a pdf
};
getPdfAsArrayBuffer(url).then(function (response) {
$scope.pdf.data = new Uint8Array(response.data);
}, function (err) {
console.log('failed to get pdf as binary:', err);
});
function getPdfAsArrayBuffer (url) {
return $http.get(url, {
responseType: 'arraybuffer',
headers: {
'foo': 'bar'
}
});
}
});
Can anyone helpe me please?
Your controller should look something like this:
angular.module('app').controller('AppCtrl', function ($scope, $sce, $http, $timeout) {
var url = 'http://example.com/file.pdf';
PDFJS.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js'
$scope.pdf = {
src: $sce.trustAsResourceUrl(url), // get pdf source from a URL that points to a pdf
data: null // get pdf source from raw data of a pdf
};
});
Remove the unnecessary code and check the console for more details.
Related
I want to get a single object from json file using AngularJs params, but it give me all objects.
This is the code I've used,
(function () {
"user strict";
angular
.module("myApp")
.controller("indexCtrl", function ($scope, $http, $routeParams) {
var workId = $routeParams.id;
$http({
url: "data/work.json",
method: "GET",
params: {id: workId}
}).then(function(sitedata) {
$scope.workDetail = sitedata.data;
});
});
})();
Please help me. Thanks
If you're loading a json file it will just return the whole content, you'll have to filter in the then callback:
$http({
url: "data/work.json",
method: "GET"
}).then(function(sitedata) {
var match = sitedata.data.filter(function(item) {
return item.id == workId;
});
if (match.length) {
$scope.workDetail = match[0];
}
});
I don't have much front-end experience, so please bear with me.
I have a local Angular app in browser (no back-end) and I want to upload a JSON file so that I can show the uploaded data on graphs. Since I don't know if I can just fs.readFile from Angular, I've chosen ng-file-upload to load the file in a nice way (from the file browser). Let me know if it isn't the right tool, though...
So I've copied the code from the official JS Fiddle on the repo. Had to modify it a bit to allow me upload anything -- remove validations.
var app = angular.module('app', ['ngFileUpload']);
app.controller('fileUploader', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
$scope.uploadFiles = function(file, errFiles) {
$scope.f = file;
$scope.errFile = errFiles && errFiles[0];
if (file) {
file.upload = Upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
data: {file: file}
});
file.upload.then(function (response) {
$timeout(function () { // don't know why this timeout
$scope.fileReady = true;
file.result = response.data;
// can't figure out what to do with this!!!
console.log('response.data:\n', JSON.stringify(response.data.result, null, 2));
});
}, function (response) {
if (response.status > 0)
$scope.fileError = response.status + ': ' + response.data;
});
}
};
}]);
The response comes out as an object I can't do much with:
[
{
"fieldName": "file",
"name": "my-awesome-data.json",
"size": "364077"
}
]
How do I get the actual data that was uploaded / parse the JSON file?
Try to get the file content using $http.get like:
$http.get(response.data).success(function(data) {
console.log(data);
});
I am new in AngularJS and I have got this problem. I have got defined service citiesService with method addCity:
.service('citiesService', ['$resource', function($resource){
this.addCity = function(city) {
var cityItem = $resource("server/?module=cities&action=add", {}, {save: {method: "POST", isArray:true}});
return cityItem.save({
city: city
});
};
}])
It works fine, the new city was successfully added into DB via the PHP script, but I don't know, how to return server response. Server returning response like:
$output = [];
$output[] = ["success" => "added to database"];
echo json_encode($output);
and then I have got this controller:
.controller('citiesAddCtrl', function($scope, $modalInstance, citiesService) {
// save addCity form (modal)
$scope.saveForm = function() {
if($scope.city.name) {
$scope.a = citiesService.addCity($scope.city);
}
}
})
but I really don't know, how to display server JSON response. When I try something like console.log($scope.a), It shown empty array, but as you can see, the server response is in the right debug menu:
Can you help me to solve this problem please? I read some Stackoverflow topics and tried some edits, which are described here, but nothing works for me.
Since save returns a promise, you could access the response as following (untested):
.controller('citiesAddCtrl', function($scope, $modalInstance, citiesService) {
// save addCity form (modal)
$scope.saveForm = function() {
if($scope.city.name) {
citiesService.addCity($scope.city).$promise.then(function(response) {
$scope.a = response
});
}
}
})
Why don't you use simply $http which has a clear promise structure?
$http({
method: 'POST',
url: "server/?module=cities&action=add",
data: $scope.city
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
See docs at $http
I have the following:
Node/Express router:
var City = require('./models/city');
module.exports = function(app) {
app.get('/cities/:zip', function(req, res) {
console.log(req.params.zip);
var query = City.find({"zip" : req.params.zip})
query.exec(function(err, city) {
if (err)
res.send(err);
console.log(city);
res.json(city);
});
});
app.get('*', function(req, res) {
res.sendfile('./public/views/index.html'); // load our public/index.html file
});
};
Angular Service:
angular.module('CityService', []).factory('City', ['$http', function($http) {
return {
get : function(zip) {
var zip = zip.zip
return $http.get('/cities/' + zip);
}
}
}]);
Angular Controller:
angular.module('CityCtrl', []).controller('CityController', ['$scope', '$http', 'City', function($scope, $http, City){
$scope.update = function (zip) {
$scope.weather = City.get({zip : zip});
if(zip.length = 5){
$http.jsonp('http://api.openweathermap.org/data/2.5/weather?zip='+ zip +',us&callback=JSON_CALLBACK').success(function(data){
$scope.data=data;
console.log(data.name);
});
}
}
}]);
Everything seems to be working fine. However, when I try to log the $scope.weather I get the entire header. I've tried logging $scope.weather.name (I know it's there) and then it returns "undefined". When I check what the server is logging it appears to log the correct JSON response. Any idea of how to get the "name" field of the returned document?
Replace $scope.weather = City.get({zip : zip}); to City.get({zip : zip}).then(function(response){$scope.weather= response.data});
As we know $http return a promise object so you must have to resolve it. you are not resolving it in service so you have to set $scope.weather in then.
I have a resource where the get is receiving an object like {metadata : {}, data : {}}. But when I save, I just want to send the data and not metadata.
.factory("$profile", function($resource) {
return $resource("service/profile/:profileid");
})
.controller('ProfileController', function($scope, $routeParams, $profile) {
$scope.profile = new $profile();
$scope.doSave = function() {
// need to send profile.data only << ----------
$scope.profile.$save($routeParams, function(data) {
console.log("saved profile");
});
}
What I have done right now is the following:
.controller('ProfileController', function($scope, $routeParams, $profile) {
$scope.profile = new $profile();
$scope.doSave = function() {
$scope.profile.data.$save = $scope.profile.$save;
$scope.profile.data.$save($routeParams, function(data) {
console.log("saved profile");
});
}
This works but I am sure there is a much cleaner way to do what I need to do. Ideally I would tell the resource to look for a data property on "save".
Yes, you can do that. The properties you need are 'transformResponse' (on GET) and 'transformRequest' (on Post).
.factory("$profile", function($resource) {
return $resource("service/profile/:profileid",
{},
{
get: {
method: 'GET',
transformResponse: function(response, headers){
return response.data;
}
},
post: {
method: 'POST',
transformRequest: function (request, headers) {
var result = request.data; // << This line might not be exactly what you need.
return result;
}
}
});
})
I actually suspect that the transformRequest part isn't needed at all (but you did ask for it).
$scope.profile.$save($routeParams, function(data) {
console.log("saved profile");
});