populate select with datajson using React js - select

I'm trying to populate a select using React js, I'm using the example given on the react js docs(https://facebook.github.io/react/tips/initial-ajax.html) , which uses jquery to manage the ajax calling, I'm not able to make it work, so far i have this:
here the codepen : http://codepen.io/parlop/pen/jrXOWB
//json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc ase_id":"CTSTESTING","name":"CTS-Testing"}]
//using jquery to make a ajax call
var App = React.createClass({
getInitialState: function() {
return {
opts:[]
};
},
componentDidMount: function() {
var source="https://api.myjson.com/bins/3dbn8";
this.serverRequest = $.get(source, function (result) {
var arrTen = result[''];
for (var k = 0; k < ten.length; k++) {
arrTen.push(<option key={opts[k]} value={ten[k].companycase_id}> {ten[k].name} </option>);
}
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
<select id='select1'>
{this.state.opts}
</select>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('root')
);
html
<div id="root"></div>
any idea how to make it works, thanks.

You need to call setState to actually update your view. Here's a workable version.
//json file called from source : [{"companycase_id":"CTSPROD","name":"CTS-Production"},{"companyc ase_id":"CTSTESTING","name":"CTS-Testing"}]
//using jquery to make a ajax call
var App = React.createClass({
getInitialState: function() {
return {
opts:[]
};
},
componentDidMount: function() {
var source="https://api.myjson.com/bins/3dbn8";
this.serverRequest = $.get(source, function (result) {
var arrTen = [];
for (var k = 0; k < result.length; k++) {
arrTen.push(<option key={result[k].companycase_id} value={result[k].companycase_id}> {result[k].name} </option>);
}
this.setState({
opts: arrTen
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
<select id='select1'>
{this.state.opts}
</select>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('root')
);

Related

changeRequest in Alloy 2.5 and Liferay 6.2 cannot be called

I am trying to migrate a portlet from Liferay 6.1 to 6.2 and forced to adapt the Alloy code to 2.5 version and the aui-pagination part:
pagination = new A.Pagination({
circular: false,
containers: '.pagination',
on: {
changeRequest: function(event) {
var newState = event.state;
this.setState(newState);
}
},
total: 10,
});
But whenever I call the changeRequest() of the pagination instance from other functions I get errors:
this._pagination.changeRequest();
Is there any solution for this?
Your question is a little strange. How would you call changeRequest() without passing an event in your example? And why set the state from the event when that's already happening automatically?
To answer the more generic question that you are asking, there are several potential solutions to calling the changeRequest() function programmatically:
Define a named function and set it to be the changeRequest() function:
function changeRequest() {
console.log('changeRequest function called!');
}
var pagination = new Y.Pagination({ /* ...your code here... */ });
pagination.on('changeRequest', changeRequest);
// OR if you don't need to access the pagination component
// in your changeRequest() method
new Y.Pagination({
/* ...your code here... */
on: {
changeRequest: changeRequest
}
});
This method will only work if you do not need to use the event parameter, or if you only use the event parameter when the actual event occurs, or if you construct the event parameter yourself.
Runnable example using your code:
YUI().use('aui-pagination', function(Y) {
var pagination = new Y.Pagination({
circular: false,
containers: '.pagination',
total: 10,
});
function changeRequest(event) {
if (event) {
alert('changeRequest called with event');
var newState = event.state;
pagination.setState(newState);
} else {
alert('changeRequest called without event');
}
}
pagination.after('changeRequest', changeRequest);
pagination.render();
Y.one('#button').on('click', function() {
changeRequest();
});
});
<script src="http://cdn.alloyui.com/2.0.0/aui/aui-min.js"></script>
<link href="http://cdn.alloyui.com/2.0.0/aui-css/css/bootstrap.min.css" rel="stylesheet"></link>
<br />
<button id="button">call <code>changeRequest()</code></button>
Call pagination.next() or pagination.prev():
YUI().use('aui-pagination', function(Y) {
// ...your code here...
pagination.next();
});
Runnable example using your code:
YUI().use('aui-pagination', function(Y) {
var pagination = new Y.Pagination({
circular: false,
containers: '.pagination',
total: 10,
on: {
changeRequest: function(event) {
alert('changeRequest called with event');
var newState = event.state;
pagination.setState(newState);
}
}
}).render();
Y.one('#button').on('click', function() {
pagination.next();
});
});
<script src="http://cdn.alloyui.com/2.0.0/aui/aui-min.js"></script>
<link href="http://cdn.alloyui.com/2.0.0/aui-css/css/bootstrap.min.css" rel="stylesheet"></link>
<br />
<button id="button">call <code>changeRequest()</code></button>
Simulate a click event on one of the pagination items:
YUI().use('aui-pagination', 'node-event-simulate', function(Y) {
// ...your code here...
pagination.getItem(1).simulate('click');
});
Runnable example using your code:
YUI().use('aui-pagination', 'node-event-simulate', function(Y) {
var pagination = new Y.Pagination({
circular: false,
containers: '.pagination',
total: 10,
on: {
changeRequest: function(event) {
alert('changeRequest called with event');
var newState = event.state;
pagination.setState(newState);
}
}
}).render();
Y.one('#button').on('click', function() {
pagination.getItem(1).simulate('click');
});
});
<script src="http://cdn.alloyui.com/2.0.0/aui/aui-min.js"></script>
<link href="http://cdn.alloyui.com/2.0.0/aui-css/css/bootstrap.min.css" rel="stylesheet"></link>
<br />
<button id="button">call <code>changeRequest()</code></button>

How to reload/refresh with infinite-scroll

I want to have a reload function but I found some difficulties.
My app should clear all data by using the reload function and grab the feed again. Event that works, but it shows me only the first 5 news (limit of my api/per page) and ignores completely the loadMore function.
factory
.factory('newsDataService', function($http) {
return {
GetPosts: function(page) {
return $http.get("http://newsapi.domain.tdl/");
},
GetMorePosts: function(page) {
return $http.get("http://newsapi.domain.tdl/?page=" + page);
}
};
})
controller
.controller('NewsCtrl', function($scope, newsDataService) {
$scope.page = 1;
$scope.noMoreItemsAvailable = false;
newsDataService.GetPosts().then(function(items){
$scope.items = [];
$scope.items = items.data.response;
});
$scope.Reload = function() {
console.log('reload');
newsDataService.GetPosts().then(function(items){
console.log(items);
$scope.items = items.data.response ;
$scope.noMoreItemsAvailable = false;
$scope.$broadcast('scroll.refreshComplete');
})
};
$scope.loadMore = function(argument) {
$scope.page++;
newsDataService.GetMorePosts($scope.page).then(function(items){
if (items.data.response) {
$scope.items = $scope.items.concat(items.data.response);
$scope.noMoreItemsAvailable = false;
} else {
$scope.noMoreItemsAvailable = true;
}
}).finally(function() {
$scope.$broadcast("scroll.infiniteScrollComplete");
});
};
})
template:
<ion-view view-title="News">
<ion-content>
<ion-refresher on-refresh="Reload()"></ion-refresher>
<div class="list">
<a collection-repeat="news in items" href="#/app/newsreader/{{news.id}}" class="item item-thumbnail-left">
<h2>{{news.headline}}</h2>
<div class="item-text-wrap" ng-bind-html="news.teaser"></div>
</a>
</div>
<ion-infinite-scroll ng-if="!noMoreItemsAvailable" on-infinite="loadMore()" distance="1%"></ion-infinite-scroll>
</ion-content>
</ion-view>
How can I resolve this?
Just found the solution on my own.
.controller('NewsCtrl', function($scope, newsDataService) {
$scope.items =[]
$scope.page = 1;
newsDataService.GetPosts().then(function(items){
$scope.items = items.data.response;
});
$scope.Reload = function() {
console.log('reload');
$scope.items =[];
$scope.page = 1;
$scope.loadMore();
};
$scope.loadMore = function(argument) {
$scope.page++;
newsDataService.GetMorePosts($scope.page).then(function(items){
if (items.data.response) {
$scope.items = $scope.items.concat(items.data.response);
$scope.noMoreItemsAvailable = false;
} else {
$scope.noMoreItemsAvailable = true;
}
}).finally(function() {
$scope.$broadcast("scroll.infiniteScrollComplete");
$scope.$broadcast('scroll.refreshComplete');
});
};
})

Ionic Local storage put information into array

Here is the code
Controller.js
$scope.addFavorite = function (index) {
$scope.temp = {
id: index
};
$scope.dish = $localStorage.getObject('favorites', '{}');
console.log($localStorage.get('favorites'));
$localStorage.storeObject('favorites', JSON.stringify($scope.temp));
var favorites = $localStorage.getObject('favorites');
console.log(favorites);
favoriteFactory.addToFavorites(index);
$ionicListDelegate.closeOptionButtons();
}
Service.js
.factory('favoriteFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
var favFac = {};
var favorites = [];
favFac.addToFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index)
return;
}
favorites.push({id: index});
};
favFac.deleteFromFavorites = function (index) {
for (var i = 0; i < favorites.length; i++) {
if (favorites[i].id == index) {
favorites.splice(i, 1);
}
}
}
favFac.getFavorites = function () {
return favorites;
};
return favFac;
}])
.factory('$localStorage', ['$window', function($window) {
return {
store: function(key, value) {
$window.localStorage[key] = value;
},
get: function(key, defaultValue) {
return $window.localStorage[key] || defaultValue;
},
storeObject: function(key, value) {
$window.localStorage[key] = JSON.stringify(value);
},
getObject: function(key,defaultValue) {
return JSON.parse($window.localStorage[key] || defaultValue);
}
}
}])
I want to make a Favorites function, and I want to put every item's ID that marked into an array.
But, it couldn't expand the array and only change the value.
Did I make something wrong on here? Or maybe I put a wrong method on here?
Thank you in advance!
I just create logic for storing object, you have to made logic for remove object from localstorage.
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script>document.write('<base href="' + document.location + '" />');</script>
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="item in items">
{{item.item_name}}
<button ng-click="addFavorite(item.id)">Add to Favorite</button>
<br><hr>
</div>
</body>
</html>
<script type="text/javascript">
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$http)
{
$scope.items = [
{id:1,item_name:'Apple'},
{id:2,item_name:'Banana'},
{id:3,item_name:'Grapes'},
]
$scope.addFavorite = function (index)
{
if(localStorage.getItem('favorites')!=undefined)
{
var old_favorite = JSON.parse(localStorage.getItem('favorites'));
var obj = {index:index};
old_favorite.push(obj);
localStorage.setItem('favorites',JSON.stringify(old_favorite));
}
else
{
var obj = [{index:index}];
localStorage.setItem('favorites',JSON.stringify(obj));
}
}
});
</script>

bootstrap typeahead url/redirect

$(function(){
var orthoObjs = {};
var orthoNames = [];
var throttledRequest = _.debounce(function(query, process){
$.ajax({
url: 'json/ortho4.json'
,cache: false
,success: function(data){
orthoObjs = {};
orthoNames = [];
_.each( data, function(item, ix, list){
orthoNames.push( item.searchPhr );
orthoObjs[ item.searchPhr ] = item;
});
process( orthoNames );
}
});
}, 300);
$(".typeahead").typeahead({
source: function ( query, process ) {
throttledRequest( query, process );
}
,updater: function (item) {
var url = "orthoObjs[item.searchUrl]";
window.location = url;
Whats the best way to get the redirect to work? I have seen similar questions, but can't get this to work. Documentation on typeahead isn't great. I am using underscore.js for the each function. Just want a simple search query that redirects when the user selects.
I actually got this to work. I got a little help... but here it is. There is the JSON file..
[
{ "id":1, "searchUrl":"invisalign.html", "name":"invisalign" }
,{ "id":2, "searchUrl":"invisalign.html", "name":"invisalign teen" }
,{ "id":3, "searchUrl":"clearbraces.html", "name":"clear braces" }
]
And the HTML code....
Lots of good stuff here.. http://fusiongrokker.com/post/heavily-customizing-a-bootstrap-typeahead
And the search code..
<form method="post" id="myForm" class="navbar-search pull-left">
<input
type="text"
class="search-query typeahead"
placeholder="Search Our Website"
autocomplete="off"
data-provide="typeahead"
/>
<i class="fa-icon-search icon-black"></i>
</form> </li>
$(function(){
var bondObjs = {};
var bondNames = [];
$(".typeahead").typeahead({
source: function ( query, process ) {
//get the data to populate the typeahead (plus an id value)
$.ajax({
url: '/json/bonds.json'
,cache: false
,success: function(data){
bondObjs = {};
bondNames = [];
_.each( data, function(item, ix, list){
bondNames.push( item.name );
bondObjs[ item.name ] = item.searchUrl;
});
process( bondNames );
}
});
}
, updater: function ( selectedName ) {
window.location.href =bondObjs[ selectedName ];
}
});
});
</script>

.each() not working in IE

I want to get all labels inside a div, the blow piece of code works in Firefox and not working IE. Any idea. Thanks in advance.
<div id='discounts'>
<label id="discount1"> discount 1</label>
<label id="discount2"> discount 2 </label>
<input type="text" id="discountmisc" value="" />
</div>
var selectLabels = {
getLabels: function() {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
}
};
selectLabels.getLabels();
Are you wrapped in DOM Ready functions? i.e.
$(function () {
var selectLabels = {
getLabels: function() {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
}
};
selectLabels.getLabels();
});
or alternately:
var selectLabels = {
getLabels: function() {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
}
};
$(selectLabels.getLabels);
or finally (because you don't care about the return value):
var selectLabels = {
getLabels: function() {
$(function () {
$('#discounts > label').each(function(index, item) {
alert(index + $(item).attr('id'));
});
});
}
};
selectLabels.getLabels();
Tell me, and if so, I'll change my answer.