How can i assign context path dynamically in angularjs - angularjs

I want to assign context path dynamically in angularjs.For example instead of giving url:'op/services/.....' in the below code i want to assign the path dynamically like we do in jsp "url:'request.getContextPath()/services/...'".Since i cant use request.getContextPath() in angularjs which function i should use instead.I dont want to hardcode it because my project requirement is in such a way that the context path might vary for different users..
$http({
'url' : '/op/services/saveTemplate',
'method' : 'GET',
'headers': {'Content-Type' : 'application/json'},
'params' : \\something
}).success(function(data){
//some function
});
In jsp we use request.getContextPath() but i am not sure which function i should use in angularjs.I searched the net but couldnt find anything...

The best way to do what you want is to either fetch the value you need with an ajax api call,or bootstrap the url in a script tag and use a global variable to refererence the url
like
<script>
window.myUrl ="<%=somejsp%>";
</script>
before loading any other script in your page.

Related

Can we submit a form multiple times without ajax

I have a JS array. Each element of that array is a form data in JSON format. I want to loop through this array and submit each form data to the server WITHOUT using AJAX. Can this be done? Any ideas would be a help.
One solution I know is Using Angualar JS service $http
$http({
method : 'POST',
url : 'clone.php or servlet or other calls',
data : $scope.user, //forms user object
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
//do something
});
References :
Angularjs - simple form submit
http://tutsnare.com/post-form-data-using-angularjs/
I don't see if you mentioned where this is executing but if it's not client side (I'm assuming server side since this is tagged CF), you could CFHTTP each item by looping through the array.

How to get URL segment in Angular JS?

I have URL's in project as:
http://blo.c/news
http://blo.c/video
How I can get segments news, video from these URL?
I tried to use $location in Angular JS, but this object has not these segments
You need to use $location.path()
// given url http://blo.c/news
var path = $location.path();
// => "/news"
If you are using HTML5 mode you must ensure $locationProvider.html5Mode(true) is set so $location works properly.
If you are not using HTML5 mode (which is the case here); then you'll need to drop to traditional javascript to get the URL, since you are not using Angular routing in the first place:
// given url http://blo.c/news
var path = window.location.pathname;
// => "/news"
You might choose to inject $window instead of using window directly, this is only a thin wrapper over the native window object but facilitates testing.
Use the $location.path function to get the url. To get what's after the url, use split
$location.path.split(/\{1}/)[1]
const URL = '/seg1/?key=value';
$location.path();// will return URI segment (in above URL it returns /seg1 ).
$location.search(); // getter will fetch URL segment after ? symbol.
//(in above URL it returns {key:value} object ).
Official Doc: https://docs.angularjs.org/guide/$location

Fetching HTML in Angular

I am getting started with Angular, and I want to get HTML template from a file using JavaScript, I don't want to use ng-include or any other directive as I don't really have an html to play with, I have only JavaScript file with data rendered from REST service and I need to send HTML output to the page I am in, so I don't really have any existing elements in the DOM.
So how do I get HTML from another file and use it just from JavaScript, in an Angular way?
I think you should use directive and as James point out use the $compile.
You can look some doc https://docs.angularjs.org/guide/compiler
If for any reason you don't want to do that, I can put an exemple of a really BAD angular code I use on my app to show the CGU (an HTML from another domain).
Note that we use jQuery, and that's not a good thing in Angular world.
$http({
method: 'GET',
url: 'URL_HTML'
}).success(function (data, status, headers, config) {
var html_from_server = $.parseHTML(data);
data = $(html_from_server.find('#container'));//look for the content of an ID.
$('#content_cgu').html(data.html());// get an element on our page and replace the html content
});
Take a look at $compile - it sounds like that's what you're looking for. You can take the html from your service and compile it to work in your AngularJS application.
Let me rephrase it. How do I get HTML from another page and store it in a variable inside my JS file using Angular? What do I do? var returnedHTML = ???
Straightforward solution:
var returnedHTML;
var url = 'http://www.google.com';
$http.get(url, { cache: $templateCache }).then(function(result){
returnedHTML = result.data;
});
I was just dealing with this today. I think your question was misunderstood.
You simply include an ng-include into your code like so:
ng-include="'https://en.wikipedia.org/wiki/Special:Random'"
Angular will display your URL as directly in the page.

How can I dynamically set templates without messy query parameters in angular ui-router?

I'm building an artist portfolio web app where the artist can create a 'project' which consists of a series of content pieces (mostly images at this point) which can then be put in an order and the artist can choose between different preset layouts. I'm using angular and node + express. I'm struggling to find a good way to dynamically set templates. The only functional scheme i've devised so far is to put the template name in a query parameter in the url like this.
ui-sref="webapp/project/photo?template=vertical"
then in ui-router it's relatively simple to set the template using state params
templateUrl : function (stateparams) {
return 'templates/' + stateparams.template + '.html';
},
Although it's functional I don't like this mostly because it creates messy urls and allows anyone to change templates with query params or more likely load something without a real template because the url was typed incorrectly or correctly without the query parameter.
I can't make an api call from the templateUrl function because it's not injectable so I can't use the $http service. I've tried to use template provider but haven't made anything functional out of that yet. It does allow for an injectable function but that function must return an entire template instead of a url. If I can get a template url for it how can a load the template with that? I assume I'm not the first person to want dynamic templates (templates set in the database) from angular. What are my best options?
I have found a functional solution to my problem using ui-router, $stateParams, and $http. I'll be looking for a better architecture scheme as this necessitates 3 server requests every time a project is requested. One to get the template name and another to load the template file and another to load the project data. I suppose I only added one request to the norm. Anyways.. This solution is working for me but next I will be moving the logic to get template by the project name to an angular service to keep everything clean.
.state('projects/:project_url', {
url : '/projects/:project_url',
templateProvider : function ($stateParams, $http) {
return $http.get('/api/projects/' + $stateParams.project_url)
.then(function (data) {
// get template name
var templateName = data.data[0].template;
// return template by name
return $http.get('/pages/' + templateName + '.html')
.then(function (data) {
return data.data;
});
});
},
controller : 'projectCtrl'
});
http://dotjem.github.io/angular-routing/ supports your scenario with inject-able template functions. Note however that you must provide the raw template in the return statement, but that is easily done using the $template service...
It is very similar to UIRouter, so it should be a fairly easy transition if you find it worth it.
http://plnkr.co/edit/dkPIWMW236ixifETohNW?p=preview
If you take the latest stable release rather than the head you must add a "get" call to that service as: $template.get('template.html') rather than the newer: $template('template.html')

Submit a URL as data in cakePHP

I am using cakePHP 1.26.
I got an Input Text box which contains a URL and I want to submit the URL and stored it in the Database using Jquery AJAX.
Here is the HTML part:
<input type="text" id="testing" value="https://stackoverflow.com/questions/ask">
This is the JQuery part:
var whatContent=$("#testing").val();
var curl="http://localhost:8080/test/grab/"+whatContent;
$.ajax({
type: "POST",
url: curl,
success: function(data) {
alert(data);}
});
This is the code for the Action in the Controller:
function grab($w=null){
if($w!=null){
return $w;
}
}
The code worked and I could see the Alert Message pop up, but there was something missing in the message. I mean I supposed to see the whole URL like this:
https://stackoverflow.com/questions/ask
But not, I just saw part of it instead:
http://stackoverflow.com
Later I altered the value in the Input Text box like this:
<input type="text" id="testing" value="https://stackoverflow.com/faq">
But again, the returned value was still
http://stackoverflow.com
cakePHP seemed to conside the URL as some parameters rather than a URL.
Please help
When you append the content to the end of your "curl" variable like you are, you are attempting to add it to be retrieved through a GET variable and will get a result in a request like http://localhost:8080/test/grab/http://stackoverflow.com/questions/ask. Clearly this is an invalid request. Your GET variable parsing is not going to be consistent and a dangerous way of passing data back to your controller (especially if users will be able to edit the appended value).
Instead, you should use the data attribute in jQuery to pass this information back in your POST request as described in the instructions here: http://api.jquery.com/jQuery.ajax/
On the Cake side, you'll be able to receive this value as $this->data['IDValueYouConfigured']. For example, if your AJAX request was like:
var whatContent=$("#testing").val();
var curl="http://localhost:8080/test/grab/";
$.ajax({
type: "POST",
url: curl,
data: "formValue="+whatContent,
success: function(data) {
alert(data);}
});
where formValue is the IDValueYouConfigured that I mentioned earlier.
More importantly, you seem to be misunderstanding proper use of the Cake framework and could be performing all of these functions MUCH more simply using things like the JsHelper, FormHelper, etc. I would recommend using the most RECENT version of Cake (1.3.3) and follow through the Blog tutorial at least once. This will lead to better questions which will be more likely to get helpful answers. Hope this helps.

Resources