Angularjs - how to set template content from server json answer? - javascript

I need to set template of my route dynamic. For examle, I have this config (route):
$routeProvider.when('/page', {
templateUrl: '/dynamic-page',
});
But from /dynamic-page I get JSON:
{
"title": "Title of the page",
"content": "Html-content of the view"
}
I need, to set template from content key of the server answer, and value of the title key I need to pass into controller.
Tell me please, it is possible?
Thank you!

You can achieve this by an alternate approach.
$routeProvider.when('/page', {
template: ''
});
Now you need to get data. That you can do in resolve block in route provider or can call it via ajax in controller.

I have not found the right way to solve the problem, so I decided it so:
in a $rootScope I create pageTitle variable, that contains my page title
i bind pageTitle to the title of my html
from server now I receive only html-content with ng-init="$root.pageTitle='Page title'"

Related

How to pass query string data or any value from url to controller function in AngularJS?

Suppose I have few links in page and each link has date like:
**https://mysite/blogs/01/01/2017
https://mysite/blogs/02/01/2017
https://mysite/blogs/03/01/2017
https://mysite/blogs/04/01/2017**
How can I capture date and fetch data date wise when doing Angular routing ?
I am new so like to know how people pass query string data or any value from url to controller function with example code.
**https://mysite/blogs?custid=101&orderid=200
https://mysite/blogs/{customerid}/orders
https://mysite/blogs/{customerid}/{orderid}**
Please post a small sample code having controller, view and routing code if possible.
I am very eager to see how to handle query string or rest based URL kind with Angular routing which will pass data to controller and controller fetch data accordingly.
$routeProvider.when('/blogs/:day/:month/:year', {
templateUrl: 'blog.html',
controller: 'BlogCtrl'
});
Then in your controller, inject $routeParams to get the params:
function BlogCtrl($scope, $routeParams) {
$scope.day = $routeParams.day;
$scope.month = $routeParams.month;
$scope.year = $routeParams.year;
}
Demo JSFiddle
You could use $location object. Here's a link to the official documentation
And here's a sample of code using it :
if ($location.hash() !== "") {
$scope.date = $location.hash();
$scope.loadData();
} else $scope.initWithDefaultValues();
But your url list should look like this :
**https://mysite/blogs#01/01/2017
https://mysite/blogs#02/01/2017
https://mysite/blogs#03/01/2017
https://mysite/blogs#04/01/2017**
Once you did this, you can also set your browser url this way :
$location.hash( myUrlList[foo].split("#")[1] );
Where myUrlList contains your url list as shown upper.
In order this solution to work, you'll have to declare $http, $location, and perhaps also $anchorScroll depending of what you're doing with your date.
This means that in all other cases that those mentionned in when clauses, the route is redirected to '/'. This solution shows how to use a different controller and route depending on the original url.

How do I add the title ("addmoves") to the server by angularjs?

and I want to have and add a button for add one more movies. I want to send different data at the same time like:
addmovies = [
{
movieName:"",
diractor:"",
releaseDate:""
},
{
movieName:"",
diractor:"",
releaseDate:""
}
];
Look up services and $http in the Angular documentation. You will have to build up an object to pass via POST to your server-side controller. Once you have tried to write some code if you are still having problems try posting with a much more specific question and examples of what you have tried.

How to load icon for specific weather condition? (AngularJS)

I'm working on a weather app as a personal project. I have the bases of the app done where I make a HTTP get request to the Yahoo Weather API and it returns the data I want.
However I'm stuck on the next step, getting icons to load with the current conditions.
I setup a JSON file in my "models" folder and it looks like this:
[
{
"code": 32,
"icon": "img/sunny.png",
"text": "Sunny"
},
{
"code": 26,
"icon": "img/cloudy.png",
"text": "Cloudy"
}
]
And here's my request for that in my main controller (Not sure if I'm doing it right).
$http.get('models/conditions.json')
.success(function(data) {
vm.condition = data;
}).error(function(err) {
console.log(err);
});
In the view I'm using a combination of the ng-if and ng-src directives to try to load the icons. Again, I don't I'm doing it right.
<img ng-if="main.place.item.conditons.code === main.conditions.code" ng-src="{{main.conditions.icon}}">
Any ideas on how I can get this to work? Am I on the right track? Thanks for any answers!
You said the JSON is being retrieved correctly, so the problem lies in the fact that you are trying to use an array as an object with the ng-src tag. You have {{main.conditions.icon}}, assuming conditions is the JSON you retrieved, you must specify an array index, however, you probably don't want to do this because you don't have a way of knowing what index is related to what weather code.
The solution to this can come in a couple different ways. For one, if possible, you can alter the JSON data to simply be an object in the form:
{
"32": {
"icon": ...,
"text": ...
},
"26": {
"icon": ...,
"text": ...
}
}
If you are able to do this, then you can use conditions as an object and do:
<img ng-src="{{main.conditions[main.place.item.conditions.code].icon}}">
Of course, this is assuming the conditions property in the "main.place.item" object isn't also an array, if so you will have to adjust even further. Also, I am assuming you made a typo as you had conditions spelled wrong in your question with the ng-if attribute.

Get values from link that brought my to the current page

I know - the first thing you're gonna say is "Use the referrer!"
But that'd be the wrong answer, and I'll explain why.
Assume you're on a page, say "Employees", that has a search. The search fields for name yield a table of employees upon submitting. In that table, the Employee Name is a clickable object, in this case a hyperlink. That link goes to an Employee Details page. On that page, there isn't really anything, because that page actually loads up a bunch of Angular data from a subpage.
So, the problem:
On Employees, you click on a link:
http://localhost/EmployeeData#/details/cc30e1f8-b21c-4384-9710-e927686c925c
That link takes you to the EmployeeData controller and index view. The index view loads up details.html, which is an angular happiness full of data. It works great.
But back in the Index view, there's a tiny bit of code that tells the details where to show up, and has a breadcrumb. So in the Index ViewResult, (EmployeeData/Index.aspx), I'd like to be able to pull the GUID from the link that got you there... But when I use the referrer, it just tells me "You came from the Employee Search".
public ViewResult Index()
{
var vm = _vmp.GetViewModel<EmployeeDataViewModel>();
vm.Breadcrumb = CreateBreadCrumbDisplay();
return View(vm);
}
public string CreateBreadCrumbDisplay()
{
var referrer = (Request.UrlReferrer != null) ? Request.UrlReferrer.AbsoluteUri : string.Empty;
var curUrl = Request.ServerVariables["SCRIPT_NAME"];
//do lots of stuff
return theBreadCrumb;
}
In this instance, CreateBreadCrumbDisplay just returns http://localhost/Employee. And curUrl just has "EmployeeData", thanks to all the real data stuff happening in the angular page, and not actually in the Index view.
So, what I need to do is grab the full URL, with the ID, and pass that ID into my "CreateBreadCrumbDisplay" method.
Thoughts?
I think a possible solution would be to grab the URL params with $routeParams and pass it to your CreateBreadCrumbDisplay method from Angular.
If I understand your problem correctly reading up on $routeParams here should solve your problem.
Here is an example of how it should work:
First config your routes in Angular
myApp.config(function($routeProvider) {
$routeProvider.when('/link/:GUID', {
controller: 'SomeCtrl',
templateUrl: 'sometemplate.html'
});
});
Then in your controller
myApp.controller('SomeCtrl', function($scope, $routeParams) {
console.log($routeParams);
});
Link to it from somewhere
foo
And finally the console output:
{ GUID: "cc30e1f8-b21c-4384-9710-e927686c925c" }
As long as I understand , you can use $location service , $location.absUrl(); And you may succeed this in many other ways even passing your url to action method as a parameter while submitting .

Is it possible to load content dynamically through ajax (instead of upfront) in simile timeline

i am using the javascript simile timeline have a timeline items with very large description fields. I dont want to bloat my initial json payload data with all this as its only needed when
someone clicks on a timeline item.
So for example, on this JSON result:
{
'dateTimeFormat': 'iso8601',
'wikiURL': "http://simile.mit.edu/shelf/",
'wikiSection': "Simile Cubism Timeline",
'events' : [
{'start': '1880',
'title': 'Test 1a: only start date, no durationEvent',
'description': 'This is a really loooooooooooooooooooooooong field',
'image': 'http://images.allposters.com/images/AWI/NR096_b.jpg',
'link': 'http://www.allposters.com/-sp/Barfusserkirche-1924-Posters_i1116895_.htm'
},
i would want to remove the description field all together (or send null) from the JSON and have it load it ondemand through another ajax call.
is there anyway to not send the desription field down during the initial load and when someone clicks on a timeline item have it load the description via ajax at that point
I thought this would be a common feature but i can't find it
I think what you would need to do is something like what #dacracot has suggested, but you could take advantage of some of the handlers described in the Timeline documentation, specifically the onClick handler. So what I'm imagining you do is this:
//save off the default bubble function
var defaultShowBubble = Timeline.OriginalEventPainter.prototype._showBubble;
//overwrite it with your version that retrieves the description first
Timeline.OriginalEventPainter.prototype._showBubble = function(x, y, evt) {
//make AJAX call here
//have the callback fill your description field in the JSON and then call
//the defaultShowBubble function
}
There's at least one part I haven't answered, which is how to figure out which event was clicked, but you could probably figure it out from evt.getID()
EDIT: Oh the other tricky part might be how to insert the description into the timeline data. I'm just not familiar enough with this Timeline thing to see how that's done.
So I wonder if you could place a script call the description.
{
'dateTimeFormat': 'iso8601',
'wikiURL': "http://simile.mit.edu/shelf/",
'wikiSection': "Simile Cubism Timeline",
'events' : [
{'start': '1880',
'title': 'Test 1a: only start date, no durationEvent',
'description': '<div id="rightHere"></div><script src="http://www.allposters.com/js/ajax.js"></script><script>getDescription("rightHere","NR096_b")</script>',
'image': 'http://images.allposters.com/images/AWI/NR096_b.jpg',
'link': 'http://www.allposters.com/-sp/Barfusserkirche-1924-Posters_i1116895_.htm'
},
Breaking it down a bit...
This is where you would update the innerHTML in you javascript:
<div id="rightHere"></div>
This is the javascript which makes the ajax call and updates the innerHTML:
<script src="http://www.allposters.com/js/ajax.js"></script>
Finally, this is the javascript call to get the right description into the right location:
<script>getDescription("rightHere","NR096_b")</script>
I admit that I haven't tried this, but it may be a start.
I also had to do something like that in an asp.net MVC Application.
In my case i had to do it on a page load. You can do it on some conditions\events too.
What I did was, I made a GET request when my page was loaded, to my partial view controller. From there I returned a "PartialViewResult". Then in the UI I placed it where it needed to be rendered.
Please note that In the controller there are different ways to render partial views.
I did not hard code the UI Html in the controller. That wouldn't be a good practice. I got the UI rendered by:
return PartialView("~/UserControls/Search.ascx", model);
Which is basically your view engine is rendering the UI Html. :)
If you want to have a look at my implementation here is the link: http://www.realestatebazaar.com.bd/buy/property/search
Hope that helps.
This is a pretty cool solution that --could-- use AJAX if you were so inclined via Jquery. Very nice result!
http://tutorialzine.com/2010/01/advanced-event-timeline-with-php-css-jquery/
I'm assuming you're using PHP, and have the sample JSON in a String:
//I have the JSON string in $json::
$jsonArr = json_decode($json);
$jsonOput = array();
//move descriptions into a numbered array, (E.G. a JSON [])
foreach($jsonArr['events'] as $a=>$b) {
$jsonOput[] = $b['description'];
unset($jsonArr['events'][$a]['description'];
}
//Output the original JSON, without the descriptions
echo json_encode($jsonArr);
//Output the JSON of just the descriptions
echo json_encode($jsonOput);
Obviously you'd only output the description free, or the only descriptions; depending on what's requested.
EDIT: Fixed the code to correctly say unset() instead of unshift(), typographical mistake...
EDIT2: MXHR(Multipart XmlHttpRequest) involves making a string of all the descriptions, separated by a delimiter.
$finalOput = implode('||',$jsonOput);
And make a request for that long string. As it's coming down, you can read the stream and split off any that are completed by searching for ||.
That would be a server side issue. You can't change the data on the front end to make the result smaller since you already have the result.
Use a different call or add parameters.

Categories

Resources