Hi I have a form in which I am sending a searched term and category id . It works fine as I am sending both things but if a user does not enter any thing only 'category id' goes, and in back end if searched term is empty all results are display to user.
But if I send an empty string in route params I redirect to myindex page. This is my app.js code.
when('/subcategory/:subcatId/:search', {
templateUrl: 'partials/subcategory.html',
controller: 'SubCategoriesController'
}).
My form
<form name="searchCategoryForm">
<div class="col-md-9 col-xs-10 col-sm-10">
<input class="form-control" placeholder="Find your item here...." ng-model="search" type="text" style="color:#09669c;">
</div>
<div class="col-md-2 col-xs-2 col-sm-2">
<a class="btn btn-primary" role="button" href='#/subcategory/{{cats[clicked_category].id}}/{{search}}'> Search</a>
</div>
</form>
My controller.js
$scope.search_term = $routeParams.search;
$scope.category_id = $routeParams.subcatId;
/* Search category form */
$scope.search_category = function () {
$http({
method: 'GET',
url: 'abc',
params: {"name": $scope.search_term, "category_id": $scope.category_id},
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': $rootScope.keyword_auth_token}
})
.success(function (data) {
$scope.search_category_result = data.items;
console.log($scope.search_category_result);
})
.error(function (data) {
console.log(data);
});
};
/* Search category form ends here*/
if ($scope.search_term && $scope.category_id)
{
$scope.search_category();
}
I believe you should mark your search terms as optional by suffixing it with a question mark (?):
when('/subcategory/:subcatId/:search?', {
templateUrl: 'partials/subcategory.html',
controller: 'SubCategoriesController'
}).
See this answer for more info: Can angularjs routes have optional parameter values?
Related
Iam creating an angular app, in which the data will be displayed based on the user details entered in login page.
In brief, I need help in acheiving the below:
When user enters username and Password, url will be built with these username and password and url will be called so that an unique id(a numeric digit) will be generated for each user. This unique id will be in a JSON format like {"Record":[{"Id":12}]}
Now if the unique id is returned from url, tab.html has to be displayed or if null is returned, an error message of wrong credentials has to be displayed.
For a successfully loggedin user, a table in tab.html will be displayed based on uniqueid which is generated from username and password.
Below is the code I have:
login.html:
<form ng-submit=submit()>
<input type="text" name="username" placeholder="Username" ng-model="person.firstName" required />
<span class="error" ng-show="mainForm.usernamename.$error.required">required</span>
<input type="password" name="pswd" placeholder="Password" ng-model="person.pswd" required />
<span class="error" ng-show="mainForm.pswd.$error.required">required</span>
<div class="submit">
<div>
<label>
<input name="remember" type="checkbox" data-ng-model="remember" data-ng-click="rememberMe()"> Remember Me
</label>
</div>
<input type="submit" value="LOGIN">
</div>
<div class="row">
<div class="col-sm-10"><p>Forgot Password?</p></div>
</div>
</form>
tab.html:
<div ng-controller="SampleController">
<table class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th>Name</th>
<th>ID</th>
<th>Qualification</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in tableContent" >
<td>{{x.Name}} </td>
<td>{{x.DT}}</td>
<td>{{x.Qualification}}</td>
</tr>
</tbody>
</table>
</div>
app.js:
var wc = angular.module('wc', []);
wc.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
.state('tab', {
url: '/tab1',
templateUrl: 'views/tab.html'
});
});
wc.controller('LoginCtrl', function ($scope,$http, $location) {
$scope.submit = function () {
$http.get("URL-PartAame=" + $scope.person.firstName + "&Password=" + $scope.person.pswd)
.success(function (data) {
//how to get the id from above url and display data based on condition//
$scope.tableData = data;
console.log(data)
$location.path('/tab1');
})
.error(function (response, status, headers, config) { });
}
});
wc.controller('SampleController', function ($scope, $http, $modal) {
$http.get("UrlA-UserId="returnedId)
.success(function (response) {
$scope.tableContent = response.Table;
});
};
I understood that this can be solved by using service or factory, but here how can a service be called along with the submit()? If this is not the correct way, please suggest the other way of doing it. Thanks in advance!!
Using $state.go and $stateParams service.
wc.controller('LoginCtrl', function ($scope,$http, $location, $state) {
$scope.submit = function () {
$http.get("URL-PartAame=" + $scope.person.firstName + "&Password=" + $scope.person.pswd)
.success(function (data) {
//how to get the id from above url and display data based on condition//
$scope.tableData = data;
console.log(data)
$state.go('tab', {id: the_necesarry_id});
//$location.path('/tab1');
})
.error(function (response, status, headers, config) { });
}
});
wc.controller('SampleController', function ($scope, $http, $modal, $stateParams) {
var returnedId = $stateParams.id;
$http.get("UrlA-UserId="returnedId)
.success(function (response) {
$scope.tableContent = response.Table;
});
};
Notice that you need add the id property contained in the $stateParams service in your url state.
.state('tab', {
url: '/tab1/:id',
templateUrl: 'views/tab.html'
});
I have simple form being opened clicking on tab
<form name="instructions" class="form form-horizontal" ng-controller="InstructionsPage">
<div class="form-group">
<label for="instruction">Instructions</label>
<textarea id="instruction" rows="5" class="form-control" ng-model="instructions">
</textarea>
</div>
<button class="btn btn-primary" data-ng-click="saveInstructions()">Save</button>
</form>
and related controller
angular.module('myApp.controllers')
.controller('InstructionsPage', ['$scope', function ($scope) {
use strict';
$scope.saveInstructions = function() {
var data = $scope.instructions;
// post request with data from textfield inside
}
}]);
How to receive data with GET-request to populate textfield with default/previously saved data? Thank you!
You can just update your $scope.instructions variable which is bound to the <textarea> ng-model from your controller like this:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.instructions = response;
}, function errorCallback(response) {
});
I am trying to do a POST request to a login api through angular js .
<form method="post" ng-submit="doLogin()">
<div class="list">
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" ng-model="loginData.user_mail">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" ng-model="loginData.password">
</label>
<label class="item">
<button class="button button-block button-positive" type="submit" >{{loginTxt}}</button>
</label>
</div>
</form>
Controller.js
$scope.doLogin=function(){
$http({
method : 'POST',
url : 'http://examplemns.com/customer/api/v1/login/login',
data : $scope.loginData, //forms user object
timeout:20000
})
.success(function(response){
alert(JSON.stringify(response));
})
.error(function(err){
console.log(JSON.stringify(err));
alert("Network error");
});
}
But i will get invalid username response even if the username and password is correct.
I checked the api through postman plugin its working fine,but when comes with angular i will get invalid.
Here is the sample input
user_mail:avm#gmail.com
password:123456
When try this input with postman plugin i will get the correct response
{
"status": 1,
"message": "Done",
"data": {
"name": "A.V.M TOURIST HOME",
"username": "avm#gmail.com",
"id": "37",
"key": "cos4ok88woo0kcw40cog0s4gg4skogscso8848ok"
}
}
but when trying through the angularjs post i with the same input i will get this response
{"status":0,"message":"Invalid username"}
Please help me:(
UPDATE
I need to transform my data to application/x-www-form-urlencoded rather than json (from comments) for that i am used this way.
var data= {user_mail:$scope.loginData.user_mail,password:$scope.loginData.password};
$http({
method : 'POST',
url : 'http://examplemns.com/customer/api/v1/login/login',
data : data,
timeout:20000
})
.success(function(response){
alert(JSON.stringify(response));
})
.error(function(err){
console.log(JSON.stringify(err));
alert("Network error");
});
But again i will get the same
Screenshot of request and response from the postman
Try this
$scope.loginData = {};
$scope.doLogin=function(){
$http({
method : 'POST',
url : 'http://examplemns.com/customer/api/v1/login/login',
data : $scope.loginData, //forms user object ,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response){
console.log(response);
})
.error(function(err){
console.log(err);
});
}
OR
$scope.loginData = {};
var data = $scope.loginData;
$http.post('/examplemns.com/customer/api/v1/login/login', data).then(successCallback, errorCallback);
ALSO TRY THIS
<input type="text" ng-model="user_mail">
<input type="password" ng-model="password">
var data = {};
data.user_mail = $scope.user_mail;
data.password = $scope.password;
$http.post('/examplemns.com/customer/api/v1/login/login', data).then(successCallback, errorCallback);
Try changing the following line:
data : $scope.loginData, //forms user object
to:
data : JSON.stringify($scope.loginData), //forms user object
I'm trying to post values from a form. Form has two fields- name and email. I have setup the controller as well but when i try to post, error is shown.
<form name="save" ng-submit="sap.saved(save.$valid)" novalidate>
<div class="form-group" >
<input type="text" name="name" id="name" ng-model="sap.name" />
</div>
<div class="form-group" >
<input type="email" name="email" id="email" ng-model="sap.email" />
</div>
<div class="form-actions">
<button type="submit" ng-disabled="save.$invalid || sap.dataLoading">Save</button>
</div>
</form>
My controller is:
(function() {
angular
.module('myApp.saved', [])
.controller('dataController', function($scope, $http) {
var sap = this;
$scope.post = {};
$scope.post.login = [];
$scope.sap = {};
$scope.index = '';
var url = 'save.php';
sap.saved = function(isValid)
{
if (isValid)
{
$http({
method: 'post',
url: url,
data: $.param({'user' : $scope.sap }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response)
{
// success
alert('success');
},
function(response)
{
// failed
alert('failed');
});
}
};
});
})();
When i submit, $ is not defined is shown. I'm pretty much new in angular. Can anyone tell what all mistakes I made?
$ is alias for jQuery and param is a jquery method.
Have you included jQuery?
data: $.param({'user' : $scope.sap }),
should be
data: {
'user': $scope.sap //POST parameters
}
data – {string|Object} – The response body transformed with the transform functions
I have a ng-model set in an (angular) Typeahead. The ng-model should pass an argument into the function linkToEvent() It passes in a number in Chrome and Safari but it doesnt in FireFox. In FF the argument is undefined.
Could someone help me with a proper solution?
Using angular JS and Siyfion/angular-typeahead.
This is my code:
HTML
<div class="col-xs-5">
<div class="form-group">
<input ng-model="eventToLink" class="typeahead" sf-typeahead type="text" datasets="eventsDataset" placeholder="zoek hier het evenement">
<button ng-click="linkToEvent(ticket.id, eventToLink.id)" class="btn btn-success btn-xs button-add-event" data-dismiss="alert">voeg toe
</button>
</div>
</div>
It passes ticket.id and eventToLink.id. For ticket.id I get a number but for eventToLink.id I get a undefined in FireFox. ticket.id is somewhere else defined in the HTML in a ng-repeat directive.
Controller JS
$scope.linkToEvent = function(ticketId, eventId){
console.log(ticketId);
// eventId gives a undefined in FireFox
console.log(eventId);
$http({
url: '/ajax/ticket/linkToEvent',
method: 'POST',
data: JSON.stringify({
'ticketId': ticketId,
'eventId': eventId
}),
header: {'Content-Type': 'application/json'}
}).success(function(data, status){
$scope.events = data.events;
$scope.something = data.something;
if (status == 200){
$scope.alerts = [];
$scope.alerts.push({type: 'danger', msg: 'OK'});
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
}
})