Search form xmlhttprequest works fine.
is there any option to use this function while typing instead of submit form ?
function customersController($scope, $http) {
$scope.search = function() {
$scope.url = 'http://www.vanmaram.com/json_result.php?en=' + $scope.keywords;
$http.get($scope.url).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in <li> element
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-csp ng-controller="customersController">
<form style="position:relative;" ng-submit="search()">
<input type="search" placeholder="Type english word" ng-model="keywords">
<input type="submit" value="Search">
</form>
<ul>
<li ng-repeat="word in result | limitTo:9">{{ word }}</li>
</ul>
</div>
Hi Please check this example in plunkr [link:http://plnkr.co/edit/6kuVR4?p=preview]
Hope it helps.
Js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.selected = "";
$scope.countries = ["India", "Australia", "Japan"];
});
app.directive('autoComplete', function($timeout) {
return function(scope, iElement, iAttrs) {
iElement.autocomplete({
source: scope[iAttrs.uiItems],
select: function() {
$timeout(function() {
iElement.trigger('input');
}, 0);
}
});
};
});
In HTML
<body ng-controller="MainCtrl">
<p>Countries {{countries|json}}!</p>
<div ng-app="MyModule">
<div>
<input auto-complete="" ui-items="countries" ng-model="selected" />selected = {{selected}}
</div>
</div>
</body>
used library jqueryui/1.8.16/jquery-ui.js
The solution found with ng-change which call the same function of form submit
function customersController($scope, $http) {
$scope.suggestword = function(argument) {
$scope.url = 'http://www.vanmaram.com/ajax_json_suggestion.php?en=' + $scope.keywords; // The url of our search
$http.get($scope.url).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.suggetionresult = data; // Show result from server in <li> element
$scope.result = null;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="" ng-csp ng-controller="customersController">
<form style="position:relative;" ng-submit="search()">
<input type="search" placeholder="Type english word" ng-model="keywords" ng-change="suggestword()">
<input type="submit" value="Search">
</form>
<ul ng-if='result.length'>
<li ng-repeat="word in result | limitTo:9">{{ word }}</li>
</ul>
<div id="suggestion" ng-if='suggetionresult.length > 1'>
Suggestions: <a ng-repeat="word in suggetionresult | limitTo:9">{{ word }}</a>
</div>
</div>
Related
I'm creating an app using fake JSONplaceholder API. I'm displaying a list of posts and I want the ng-repeated post titles to link to the post view.
Here's the HTML:
<body layout="column" ng-app="myApp" ng-cloak ng-controller="controller">
<h1>{{apptitle}}</h1>
<script type="text/ng-template" id="allposts.htm">
<a href="#addpost">
<button type="button" class="btn btn-primary addbtn" ng-model="singleModel" uib-btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0">
Add a post
</button>
</a>
View
<select ng-model="viewby" ng-change="setItemsPerPage(viewby)">
<option>9</option>
<option>18</option>
<option>36</option>
<option>100</option>
</select>posts
<div class="row" ng-repeat="collatedPostList in collatedPosts">
<div class="onepost col-xs-4 box" ng-repeat="post in collatedPostList">
<div class="inner">
{{post.title}}
<p>{{post.body | limitTo: 60}}{{post.body.length < 20 ? '' : '...'}}</p>
</div>
</div>
</div>
<div class="text-center">
<ul uib-pagination total-items="totalItems" ng-model="currentPage" class="pagination-sm"
items-per-page="itemsPerPage" ng-change="pageChanged(currentPage)"></ul>
</div>
</script>
<script type="text/ng-template" id="posts.htm">
</script>
<script type="text/ng-template" id="addpost.htm">
<form ng-submit="addPost()" class="adding">
<input id="titleadd" type="text" name="title" ng-model="newPost.title" placeholder="Add title">
<br>
<input id="textadd" type="text" name="body" ng-model="newPost.body" placeholder="Add some text">
<br>
<button type="submit" ng-click="addAlert(msg,'success')" class="btn btn-primary" id="submit" value="Submit">
Post it
</button>
<a href="#allposts">
<button type="button" class="btn btn-primary" >
Go back to post list
</button></a>
<br>
<uib-alert
ng-repeat="alert in alerts"
type="{{alert.type}}"
dismiss-on-timeout="5000"
close="alerts.splice($index, 1);">{{alert.msg}}
</uib-alert> </form>
</script>
<div ng-view></div>
<script src="app.js"></script>
</body>
and JS:
Array.prototype.collate = function(collateSize) {
var collatedList = [];
if (collateSize <= 0) {
return [];
}
angular.forEach(this, function(item, index) {
if (index % collateSize === 0) {
collatedList[Math.floor(index / collateSize)] = [item];
} else {
collatedList[Math.floor(index / collateSize)].push(item);
}
});
return collatedList;
};
var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap']);
myApp.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'allposts.htm',
controller: 'PostsController'
}).when('/posts', {
templateUrl: 'posts.htm',
controller: 'PostController'
}).when('/addpost', {
templateUrl: 'addpost.htm',
controller: 'AddController'
}).otherwise({
redirectTo: '/'
});
});
myApp.controller('PostsController', function($scope) {});
myApp.controller('PostController', function($scope) {});
myApp.controller('AddController', function($scope) {});
myApp.controller('controller', function($scope, $http) {
$scope.apptitle = "My app";
$http({
method: 'GET',
url: "http://jsonplaceholder.typicode.com/posts"
}).then(function(response) {
$scope.posts = response.data;
$scope.viewby = 9;
$scope.totalItems = $scope.posts.length;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewby;
$scope.maxSize = 5;
$scope.collatedPosts = getCollatedPosts($scope.posts);
$scope.newPost = {};
function getCollatedPosts(posts) {
if (!posts) {
return [];
}
var paginatedPosts = posts.slice((($scope.currentPage - 1) * $scope.itemsPerPage), (($scope.currentPage) * $scope.itemsPerPage));
return paginatedPosts.collate(3);
}
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.setItemsPerPage = function(num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first page
$scope.collatedPosts = getCollatedPosts($scope.posts);
};
$scope.pageChanged = function(currentPage) {
$scope.currentPage = currentPage;
$scope.collatedPosts = getCollatedPosts($scope.posts);
};
$scope.addPost = function(){
$http.post("http://jsonplaceholder.typicode.com/posts",{
title: $scope.newPost.title,
body: $scope.newPost.body,
usrId: 1
})
.success(function(data, status, headers, config){
console.log(data);
$scope.posts.push($scope.newPost);
$scope.newPost = {};
})
.error(function(error, status, headers, config){
console.log(error);
});
};});
$scope.alerts = [];
$scope.msg = "Well done! Your post was added";
$scope.addAlert = function(msg, type) {
$scope.alerts.push({
msg: msg,
type: type
});
};
});
My code is not working. There is 100 ng-repeated posts and I want each post title to link to the post view. Current code links every title to #/posts. I also tried {{post.title}}, but with no success.
What is the correct way to do this?
You can see full code here:
Do following changes::
Codepen :http://codepen.io/ruhul/pen/mAJLEo
1) Remove "/" from your href and use post.id (I believe on a click of link, you will be doing some of the database calls based on postID and will render it to UI ).
<div class="onepost col-xs-4 box" ng-repeat="post in collatedPostList track by $index"> <div class="inner"> {{post.title}} <p>{{post.body | limitTo: 60}}{{post.body.length < 20 ? '' : '...'}}</p> </div>
2) As you are passing parameter add your routing configuration as below::
You can later use this parameter in controller using $routeParams.
.when('/posts/:postId', { templateUrl: 'posts.htm', controller: 'PostController' })
3) Change your controller to this::
myApp.controller('PostController', function($scope,$routeParams,$http) {
console.log($routeParams.postId)
$http({
method: 'GET',
url: "http://jsonplaceholder.typicode.com/posts/"+$routeParams.postId
}).then(function(response) {$scope.post=response.data});
});
I'm creating an app in which one of the views contains a form that should add a post. I'm using the fake JSONplaceholder API. The resources are not really created on the server but it is faked as if. I'm using console.log to return the title and body of the post I'm creating, but only an ID shows in the console, like so: Object {id: 101}
Here's my code:
<body layout="column" ng-app="myApp" ng-cloak ng-controller="controller">
<h1>{{apptitle}}</h1>
<script type="text/ng-template" id="allposts.htm">
<a href="#addpost">
<button type="button" class="btn btn-primary" ng-model="singleModel" uib-btn-checkbox btn-checkbox-true="1" btn-checkbox-false="0">
Add a post
</button>
</a>
View
<select ng-model="viewby" ng-change="setItemsPerPage(viewby)">
<option>9</option>
<option>18</option>
<option>36</option>
<option>100</option>
</select>posts
<div class="row" ng-repeat="collatedPostList in collatedPosts">
<div class="onepost col-xs-4 box" ng-repeat="post in collatedPostList">
<div class="inner">
{{post.title}}
<hr>
<p>{{post.body | limitTo: 60}}{{post.body.length < 20 ? '' : '...'}}</p>
</div>
</div>
</div>
<div class="text-center">
<ul uib-pagination total-items="totalItems" ng-model="currentPage" class="pagination-sm"
items-per-page="itemsPerPage" ng-change="pageChanged(currentPage)"></ul>
</div>
</script>
<script type="text/ng-template" id="post.htm">
</script>
<script type="text/ng-template" id="addpost.htm">
<form ng-submit="submit()" class="adding">
<input id="titleadd" type="text" name="title" ng-model="title" placeholder="Add title">
<br>
<input id="textadd" type="text" name="body" ng-model="body" placeholder="Add some text">
<br>
<button type="submit" class="btn btn-primary" id="submit" value="Submit">
Post it
</button>
<a href="#allposts">
<button type="button" class="btn btn-primary" >
Go back to post list
</button></a>
</form>
</script>
<div ng-view></div>
<script src="app.js"></script>
</body>
JS:
Array.prototype.collate = function(collateSize) {
var collatedList = [];
if (collateSize <= 0) {
return [];
}
angular.forEach(this, function(item, index) {
if (index % collateSize === 0) {
collatedList[Math.floor(index / collateSize)] = [item];
} else {
collatedList[Math.floor(index / collateSize)].push(item);
}
});
return collatedList;
};
var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap']);
myApp.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'allposts.htm',
controller: 'PostsController'
}).when('/post', {
templateUrl: 'post.htm',
controller: 'PostController'
}).when('/addpost', {
templateUrl: 'addpost.htm',
controller: 'AddController'
}).otherwise({
redirectTo: '/'
});
});
myApp.controller('PostsController', function($scope) {});
myApp.controller('PostController', function($scope) {});
myApp.controller('AddController', function($scope) {});
myApp.controller('controller', function($scope, $http) {
$scope.apptitle = "Kansi app";
$http({
method: 'GET',
url: "http://jsonplaceholder.typicode.com/posts"
}).then(function(response) {
$scope.posts = response.data;
$scope.viewby = 9;
$scope.totalItems = $scope.posts.length;
$scope.currentPage = 1;
$scope.itemsPerPage = $scope.viewby;
$scope.maxSize = 5;
$scope.collatedPosts = getCollatedPosts($scope.posts);
});
$scope.submit = function(){
$http({
method:'POST',
url:"http://jsonplaceholder.typicode.com/posts",
data : {
title: $scope.title,
body: $scope.body
},
headers: {
'Content-Type': 'application/json'
}
})
.success(function(response){
$scope.result = response;
console.log($scope.result);
})
.error(function(){
console.log("error");
});
};
function getCollatedPosts(posts) {
if (!posts) {
return [];
}
var paginatedPosts = posts.slice((($scope.currentPage - 1) * $scope.itemsPerPage), (($scope.currentPage) * $scope.itemsPerPage));
return paginatedPosts.collate(3);
}
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.setItemsPerPage = function(num) {
$scope.itemsPerPage = num;
$scope.currentPage = 1; //reset to first page
$scope.collatedPosts = getCollatedPosts($scope.posts);
};
$scope.pageChanged = function(currentPage) {
$scope.currentPage = currentPage;
$scope.collatedPosts = getCollatedPosts($scope.posts);
};
});
Network:
There are no errors in the console. Why only the id is returning?
Though the screenshot is truncated, it is clearly seen that Request payload is empty object. So it doesn't send title and body fields, it doesn't receive them.
Angular can't just discard data object for no reason. It serializes it with JSON.stringify. title and body object properties (equal to $scope.title and $scope.body respectively) can be omitted on one condition. This happens if they are undefined.
I was given the following code to use to get the data I need, but it is not working for me. What am I doing wrong here. I have tried many things from the Angular.js docs and other stack overflow posts, but nothing has worked for me.
someurl
header: Content-Type = application/json
Pass in the following json:
{
"userID": "SomeUSER",
"password": "SomePSWD"
}
Below is the code I am using and it is not working.
function getGroup($scope, $http) {
$http.get('SOMEURL?callback=JSON_CALLBACK&userID=SomeUSER&password=SomePSWD ').
success(function(data) {
$scope.group = data;
});
}
this angularjs demo app show how to use http.jsonp
var httpJsonDemoController = angular.module('HttpJsonDemo', []);
httpJsonDemoController.controller('DataController', ['$scope', '$http', function($scope, $http) {
$http.jsonp("http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Waseem%20Hero").
success(function(data) {
$scope.data = data;
$scope.name = data.name;
$scope.salutation = data.salutation;
$scope.greeting = data.greeting;
}).
error(function (data) {
$scope.data = "Request failed";
});
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
<div id="wrapper" ng-app="HttpJsonDemo">
<div ng-controller="DataController">
<pre ng-model="data">
{{data}}
</pre>
<input ng-model='name' />
{{name}}
<input ng-model='salutation' />
{{salutation}}
<input ng-model='greeting' />
{{greeting}}
</div>
</div>
I want to get the data for three get URIs. In the form, the user enters a date which is used to retrieve three different datas from different URIs using the date user has entered. How ever this does not work. Below is my current code that I have written, but it does not work.
In simple words, The user selects a date, which is passed onto the URI and data is retrieved from the API, this happens in three functions, I want all three functions to run when the user clicks fetch.
HTML:
<div style="text-align: center" type="text/ng-template" ng-controller="DailyCtrl" class="users">
<h1>{{message}}</h1>
<form style="text-align: center" name="myform" id="myform1" ng-submit="fetch()" >
<input type="date"
ng-model="date"
value="{{ 'date' | date: 'dd/MM/yyyy' }}" />
<div><center><button type="submit" >Fetch</button></center></div>
</form>
{{formdata.date}}
<ul ng-controller="NewCooliosCtrl" ng-repeat="newCoolio in newCoolios.newCoolios">
<li>{{newCoolio.personID}}, {{newCoolio.placeID}}, {{newCoolio.datePlaced}}</li>
</ul>
<ul ng-controller="NewPlacesCtrl" ng-repeat="newPlace in newPlaces.newPlaces">
<li>{{newPlace}} </li>
</ul>
<ul ng-controller="NewUsersCtrl" ng-repeat="newUser in newUsers.newUsers">
<li>New Users: {{newUser}} </li>
</ul></br></br>
</div>
Angularjs:
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.when('/getdailydata', {
templateUrl: 'templates/getnewcoolios.html',
controller: 'DailyCtrl'
})
}])
.controller('DailyCtrl', function ($scope) {
$scope.toFetch = [];
$scope.fetch = function () {
for (var i = 0; i < $scope.toFetch.length; i++) {
$scope.toFetch[i]();
}
}
})
.controller('NewUsersCtrl', function ($scope, $http, $filter) {
$scope.fetch = function () {
var formdata = {
'date': $filter('date')(this.date, 'dd/MM/yyyy')
};
var inserturl = 'http://94.125.132.253:8001/getnewusers?date=' + formdata.date;
$http.get(inserturl).success(function (data) {
console.log(formdata);
$scope.newUsers = data;
console.log(inserturl);
console.log(data);
$scope.message = 'List of New Users';
})
}
$scope.toFetch.push($scope.fetch);
})
.controller('NewPlacesCtrl', function ($scope, $http, $filter) {
$scope.fetch = function () {
var formdata = {
'date': $filter('date')(this.date, 'dd/MM/yyyy')
};
var inserturl = 'http://94.125.132.253:8001/getnewplaces?date=' + formdata.date;
$http.get(inserturl).success(function (data) {
console.log(formdata);
$scope.newPlaces = data;
console.log(inserturl);
console.log(data);
$scope.message = 'List of New places';
})
}
$scope.toFetch.push($scope.fetch);
})
.controller('NewCooliosCtrl', function ($scope, $http, $filter) {
$scope.fetch = function () {
var formdata = {
'date': $filter('date')(this.date, 'dd/MM/yyyy')
};
var inserturl = 'http://94.125.132.253:8001/getnewcoolios?date=' + formdata.date;
$http.get(inserturl).success(function (data) {
console.log(formdata);
$scope.newCoolios = data;
console.log(inserturl);
console.log(data);
$scope.message = 'List of New Coolios';
})
}
$scope.toFetch.push($scope.fetch);
})
That should be in a service really as charlietfl pointed out - but can you not simplify the whole thing down and do something along the lines of (pseudo code!!!) :
.controller('DailyCtrl', function ($scope, $filter, $http) {
$scope.newCoolios = [];
$scope.newPlaces = [];
$scope.newUsers = [];
$scope.date;
$scope.fetch = function(){
var parsedDate = 'date': $filter('date')(this.date, 'dd/MM/yyyy');
$http.get('http://94.125.132.253:8001/getnewusers?date=' + parsedData.date).success(function (data) {
$scope.newUsers = data;
});
$http.get('http://94.125.132.253:8001/getnewplaces?date=' + parsedData.date).success(function (data) {
$scope.newPlaces = data;
});
$http.get('http://94.125.132.253:8001/getnewusers?date=' + parsedData.date).success(function (data) {
$scope.newUsers = data;
});
}
});
The the html could be something like....
<div style="text-align: center" type="text/ng-template" ng-controller="DailyCtrl" class="users">
<h1>{{message}}</h1>
<input type="date" ng-model="date" value="{{ 'date' | date: 'dd/MM/yyyy' }}" />
<button ng-click="fetch()">Update</button>
<ul ng-repeat="newCoolio in newCoolios">
<li>{{newCoolio.personID}}, {{newCoolio.placeID}}, {{newCoolio.datePlaced}</li>
</ul>
<ul ng-repeat="newPlace in newPlaces">
<li>{{newPlace}} </li>
</ul>
<ul ng-repeat="newUser innewUsers">
<li>New Users: {{newUser}} </li>
</ul>
</div>
Im trying to push a data value to an array in AngularJS, with .push();, but I always get this error message:
Error: $scope.test.push is not a function
Here is my HTML:
<div ng-controller="Test">
<div class="container">
<div class="col-sm-9 col-sm-offset-2">
<div class="page-header"><h1>Testar</h1></div>
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Sträcka</th>
<th>Tid</th>
</tr>
</thead>
<tr ng-repeat="info in test"><td>{{info.stracka}}</td><td>{{info.tid}}</td></tr>
</table>
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate> <!-- novalidate prevents HTML5 validation since we will be validating ourselves -->
<div class="form-group" ng-class="{'has-error' : userForm.stracka.$invalid && !userForm.stracka.$pristine, 'has-success' : userForm.stracka.$valid }">
<label>Sträcka(m):</label>
<input type="text" name="stracka" class="form-control" ng-model="form.stracka" required>
<p ng-show="userForm.stracka.$invalid && !userForm.stracka.$pristine" class="help-block">Fel sträcka</p>
</div>
<div class="form-group" ng-class="{'has-error' : userForm.tid.$invalid && !userForm.tid.$pristine, 'has-success' : userForm.tid.$valid && !userForm.tid.$pristine}">
<label>Tid:</label>
<input type="text" name="tid" class="form-control" ng-model="form.tid" ng-minlength="3" ng-maxlength="8">
<p ng-show="userForm.tid.$error.minlength" class="help-block">För kort</p>
<p ng-show="userForm.tid.$error.maxlength" class="help-block">För långt</p>
</div>
<button type="submit" class="btn btn-primary">Lägg till</button>
</form>
</div>
</div>
</div>
And here is my controller:
as.controller('Test', function($scope, $http, $rootScope, testFactory)
{
$http.get($rootScope.appUrl + '/nao/test/test')
.success(function(data, status, headers, config) {
$scope.test = data.data;
});
$scope.form = {};
$scope.submitForm = function(isValid) {
if(isValid)
{
/*testFactory.testFactoryMethod(function($http) {
$scope.test = data;
});*/
$http.post($rootScope.appUrl + '/nao/test', $scope.form)
.success(function(data, status, headers, config) {
console.log(data);
$scope.test.push($scope.form);
}).error(function(data, status) {
});
}
};
});
Can anyone help me and explain why I get this message?
Try doing this:
$scope.test = [];
$scope.test.push($scope.form);
Try this:
as.controller('Test', function($scope, $http, $rootScope, testFactory)
{
$http.get($rootScope.appUrl + '/nao/test/test')
.success(function(data, status, headers, config) {
$scope.test = data.data;
});
$scope.form = {};
$scope.submitForm = function(isValid) {
if(isValid)
{
/*testFactory.testFactoryMethod(function($http) {
$scope.test = data;
});*/
$http.post($rootScope.appUrl + '/nao/test', $scope.form)
.success(function(data, status, headers, config) {
console.log(data);
$scope.test = $scope.test || [];
$scope.test.push($scope.form);
}).error(function(data, status) {
});
}
};
});
create an array first -
$scope.usermsg = [];
then push value in it -
$scope.usermsg.push($variable);