Angular JS from rs.send() - javascript

Im generating some html code with angular in it, lets say it look something like this
exports.someApi = function(req,res){
res.send('<p>some html {{ "ENTER-PASSWORD" | translate }} </p>');
}
and in my controller im doing this
$http({method: 'GET', url: '/someapi'}).
success(function(data, status, headers, config) {
console.log(data);
$('.testPrint').html(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
the problem is, I get resposne rigth, but angular code is not executed it print this in html
some html {{ "ENTER-PASSWORD" | translate }}
it should write some html enter password
How to do this?

This is not the way to go with Angular. Specifically, $(...).html(data) will set the data directly to DOM, bypassing Angular's compilation step. This step is where the "magic" happens" (i.e. in your case the {{...}} get bound to the model).
Some ways to do it:
Make a directive and use templateUrl: "/someapi". When the directive is to be displayed, Angular will load /someApi and compile it.
Use ng-include="'/someApi'" (note single quotes within double quotes; this is intentional). Maybe together with ng-if to hide the content when not wanted.
The ui-router provides advanced facilities for subview navigation that may suit your needs.
A must-read is this great answer.

Related

Failing to show an individual entry from an API in Angular

I'm building my first little AngularJS app.
I'm successfully able to show all entries from the API on the home page of the app.
Then I'm routing the user via ng-href to /jobs/{{job.id}} and have the appropriate controller to do that.
My console.log statement is telling me that the correct entry is being loaded via the GET request method but the template isn't actually pulling that back for display.
Here's the extent of what I have so far http://plnkr.co/QPW3lsLHfPxyYOKcVOKY (obviously my API isn't public) but wondering if there's something obvious I'm missing in my show template relating to the showController perhaps?
I've been working along with CodeSchool but I've had to make some mods to their code (for example the showController wasn't correctly defining $http or $routeParams).
Help appreciated.
So it seems there's an issue between the tutorial version of Angular 1.3.x and the one I'm using 1.4.x
However, using this works as sweet as a nut, passing $scope as a function parameter
angular.module('JobStore')
.controller('JobsShowController', function($http, $routeParams, $scope) {
$http({
method: 'GET',
url: '/jobs/' + $routeParams.id + '.json'
}).success(function(data) {
$scope.job = data;
console.log(data);
});
})

AngularJS and serverside filter and pagination

I'm looking to use Angular JS with WebAPI - will be returning a large number of results from the WebAPI and so want to use some sort of server-side pagination and filtering.
Most of the tutorials i've seen are for client side filtering which isn't what i'm looking for.
Not really used AngularJS before, so looking for a simple example which can show how to utilise this - effectively i have a list of products and want to be able to for example filter by price. As it's a large data set i'd want to utilise pagination as well.
At the moment, in my controller I have:
app.controller("MyController", function ($scope, $http){
$http.get('/api/ProductResults').
success(function (data, status, headers, config) {
$scope.results = data.results;
}).
error(function (data, status, headers, config) {
// log error
});
which will return a list of products and i will use to output a list.
The WebAPI will take parameters for page number and filters etc. but i'm not sure how to implement this in the code.
$http.get('/api/Products?page=1&minPrice=10')
I'd expect that i would get the current page number and min price from the URL parameters?
For the page number and minPrice, you could have scope variables that hold that info for you. Let's say you have a data grid on the page that includes navigation for the several pages of data you have. In this case, I would have a $scope.pageNumber variable bound to that data grid navigation item. A click on next or previous changes the value of $scope.pageNumber and on you $http you would use that $scope.pageNumber when constructing your request URL. The same goes for minPrice.
You can add your parameters to your request like this:
$http({
url: "/api/Products",
method: "GET",
params: {page : 1, minPrice : 10}
});

Angular http.get doesn't like text files with square brackets at beginning and end

I have some Angular code that is grabbing a text file from S3 and then displaying it, but the http call gives an error if the text file starts and ends with something that looks like tags inside square brackets. So here is the code:
$http.get(url).success(function(data, status, headers, config) {
console.log("success " + data);
}).
error(function(data, status, headers, config) {
console.log("error");
});
and then a file which generates an error would be this:
[image: image1.png]
lispum iupsum oeri lispum iupsum oeri
[image: image1.png]
It has me vexed, and does not happening if there is only a "tag" at the top of the file or at the bottom, there has to be both it seems. Remove either and things work instantly. Anyone have an idea why this might be or a workaround?
If I console.log the errors inside the error routine, the data, status and headers are all set to undefined. And I also get this Angular error:
SyntaxError: Unexpected token i
at Object.parse (native)
at oc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:14:156)
at Yb (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:77:125)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:77:487
at s (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:7:302)
at Yc (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:77:469)
at c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:79:109)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:112:276
at l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:126:84)
at l.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:123:195)
Since the angular $http service is attempting to parse your data using JSON pattern matches, when it encounters a stream from the server which starts with a [ and ends with a ], it will interpret it as a JSON array and attempt to build an object representation of the data, which clearly isn't possible.
you can build a custom transformResponse parameter in your $http.get() to process your data in a different manner than the traditional parser. Something like this might work (note: not tested):
$http.get(url,
{
transformResponse: function(data){
//normally we would take the raw data here and do transformations on it,
//but in your situation, you don't want any transformations done.
return data;
}
}).success(function(data, status, headers, config) {
console.log("success " + data);
...
essentially, instead of allowing angular to parse the data, we are taking the transformResponse and ensuring that the data stays the way it came in.

how to get data from controller to $scope in mvc using angularjs

I am new to angular js, I am using angular js with mvc5 application. I have created a module and controller in the js for angular. I have one action "View" in customer controller(MVC5). We need to show the all the customer in this view and i want to use "ng-repeat" here.
My problem is i am getting collection of customer as model, previously i was making foreach loop of model to show the customers. Now how i can add model into $scope data container so that i can use in ng-repeat.
What you have been doing till now is rendering the customers collection on server straight to the HTML returned to the client. What you want to do ideally is to render the HTML without the customers collection and have a call over $http service to your API controller to give you the data. From there is is easy, you
I suggest reading:
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
https://docs.angularjs.org/api/ng/service/$http
https://docs.angularjs.org/api/ng/directive/ngRepeat
Using $http in your controllers is far away from the best practice, but for simplification...the $http call in your controller could look like this:
$http({method: 'GET', url: '/api/customers'}).
success(function(data, status, headers, config) {
$scope.customers = data;
}).
error(function(data, status, headers, config) {
alert('error');
});
Then you ngRepeat in the view:
<ul>
<li ng-repeat="customer in customers">
{{customer.name}}
</li>
</ul>
For getting the data you need the http module to make call to server
https://docs.angularjs.org/api/ng/service/$http
you should be doing this via an api request to an MVC controller function that is returning json to your frontend and than use the data with $http or $resource to feed it into your controller.

parsing JSONP $http.jsonp() response in angular.js

I am using angular's $http.jsonp() request which is successfully returning json wrapped in a function:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";
$http.jsonp(url).
success(function(data, status, headers, config) {
//what do I do here?
}).
error(function(data, status, headers, config) {
$scope.error = true;
});
How to access/parse the returned function-wrapped-JSON?
UPDATE: since Angular 1.6
You can no longer use the JSON_CALLBACK string as a placeholder for
specifying where the callback parameter value should go
You must now define the callback like so:
$http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})
Change/access/declare param via $http.defaults.jsonpCallbackParam, defaults to callback
Note: You must also make sure your URL is added to the trusted/whitelist:
$sceDelegateProvider.resourceUrlWhitelist
or explicitly trusted via:
$sce.trustAsResourceUrl(url)
success/error were deprecated.
The $http legacy promise methods success and error have been deprecated and will be removed in v1.6.0. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.
USE:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
var trustedUrl = $sce.trustAsResourceUrl(url);
$http.jsonp(trustedUrl, {jsonpCallbackParam: 'callback'})
.then(function(data){
console.log(data.found);
});
Previous Answer: Angular 1.5.x and before
All you should have to do is change callback=jsonp_callback to callback=JSON_CALLBACK like so:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
And then your .success function should fire like you have it if the return was successful.
Doing it this way keeps you from having to dirty up the global space. This is documented in the AngularJS documentation here.
Updated Matt Ball's fiddle to use this method: http://jsfiddle.net/subhaze/a4Rc2/114/
Full example:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data.found);
});
The MOST IMPORTANT THING I didn't understand for quite awhile is that the request MUST contain "callback=JSON_CALLBACK", because AngularJS modifies the request url, substituting a unique identifier for "JSON_CALLBACK". The server response must use the value of the 'callback' parameter instead of hard coding "JSON_CALLBACK":
JSON_CALLBACK(json_response); // wrong!
Since I was writing my own PHP server script, I thought I knew what function name it wanted and didn't need to pass "callback=JSON_CALLBACK" in the request. Big mistake!
AngularJS replaces "JSON_CALLBACK" in the request with a unique function name (like "callback=angular.callbacks._0"), and the server response must return that value:
angular.callbacks._0(json_response);
This was very helpful. Angular doesn't work exactly like JQuery. It has its own jsonp() method, which indeed requires "&callback=JSON_CALLBACK" at the end of the query string. Here's an example:
var librivoxSearch = angular.module('librivoxSearch', []);
librivoxSearch.controller('librivoxSearchController', function ($scope, $http) {
$http.jsonp('http://librivox.org/api/feed/audiobooks/author/Melville?format=jsonp&callback=JSON_CALLBACK').success(function (data) {
$scope.data = data;
});
});
Then display or manipulate {{ data }} in your Angular template.
This should work just fine for you, so long as the function jsonp_callback is visible in the global scope:
function jsonp_callback(data) {
// returning from async callbacks is (generally) meaningless
console.log(data.found);
}
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=jsonp_callback";
$http.jsonp(url);
Full demo: http://jsfiddle.net/mattball/a4Rc2/ (disclaimer: I've never written any AngularJS code before)
You still need to set callback in the params:
var params = {
'a': b,
'token_auth': TOKEN,
'callback': 'functionName'
};
$sce.trustAsResourceUrl(url);
$http.jsonp(url, {
params: params
});
Where 'functionName' is a stringified reference to globally defined function. You can define it outside of your angular script and then redefine it in your module.
For parsing do this-
$http.jsonp(url).
success(function(data, status, headers, config) {
//what do I do here?
$scope.data=data;
}).
Or you can use
`$scope.data=JSON.Stringify(data);
In Angular template you can use it as
{{data}}
for me the above solutions worked only once i added "format=jsonp" to the request parameters.
I'm using angular 1.6.4 and answer provided by subhaze didn't work for me. I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl. Full code:
var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
url = $sce.trustAsResourceUrl(url);
$http.jsonp(url, {jsonpCallbackParam: 'callback'})
.then(function(data){
console.log(data.found);
});

Categories